如何通过单击按钮隐藏和显示表格?

Posted

技术标签:

【中文标题】如何通过单击按钮隐藏和显示表格?【英文标题】:How to hide and show table by click on button? 【发布时间】:2021-03-19 17:08:38 【问题描述】:

这是我的index.html 文件:

<button id="getAllGroups" type="button" class="btn btn-primary">Groups</button>

<div class="container">
    <h2 align="center">LESSONS</h2>
    <table class="table table-dark" border="1"  cellpadding="5">
        <thead>
        <th>GROUP ID</th>
        <th>GROUP NAME</th>
        </thead>
        <tbody id="tbody">

        </tbody>
    </table>
</div>

在我的js 文件下方:

GET: $(document).ready(
function () 

    // GET REQUEST
    $("#getAllGroups").click(function (event) 
        event.preventDefault();
        ajaxGet();
    );

    // DO GET
    function ajaxGet() 
        $.ajax(
            type: "GET",
            url: "checkGroups",
            success: function (result) 
                if (result.status == "success") 
                     var custList = "";
                    $.each(result.data,
                        function (i, group) 

                            var Html = "<tr>" +
                            "<td>" + group.groupId + "</td>" +
                            "<td>" + group.groupName + "</td>" +
                            "</tr>";
                            console.log("Group checking: ", group);
                            $('#tbody').append(Html);
                        );
                    console.log("Success: ", result);

                 else 
                    console.log("Fail: ", result);
                
            ,
                        );
    
)

休息控制器:

@RestController
public class GroupController 
@Autowired
GroupService groupService;
@GetMapping("/checkGroups")
public ResponseEntity<Object> getAllGroups() 
ServiceResponse<List<Group>> response = new ServiceResponse<>("success", groupService.getAll());
return new ResponseEntity<Object>(response, HttpStatus.OK);


我的代码有效,但 th :组 ID 和组名称在页面上,即使我没有点击按钮 Groups,但我需要我的表格仅在点击按钮后显示。 如果我不点击按钮,表格应该是隐藏的。

提前感谢您的回复。

【问题讨论】:

【参考方案1】:

我需要我的表格仅在单击按钮后显示。如果我不点击按钮,表格应该是隐藏的。

在这种情况下,使用 CSS 在页面加载时隐藏表格,并在单击按钮时使用 show() 显示它:

.container table  display: none; 
// in the $.ajax success handler:
let html = result.data.map(g => `<tr><td>$g.groupId</td><td>$g.groupName</td></tr>`;
$('#tbody').append(html);
$('.container table').show();

请注意在上面的示例中使用map() 来构建您的HTML 的简化且性能更高。

【讨论】:

以上是关于如何通过单击按钮隐藏和显示表格?的主要内容,如果未能解决你的问题,请参考以下文章

通过单击按钮显示消息,但我如何通过单击按钮隐藏此消息

如何使用操作按钮在 R Shiny 中显示和隐藏表格输出?

如何通过单击按钮并返回原始形式隐藏其右侧/左侧网格时的全宽网格?

excel如何设置背景颜色

单击按钮时如何隐藏/显示 div?

单击每个字段时如何显示和隐藏离子卡?