【问题标题】: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" width="100%" 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,但我需要我的表格仅在点击按钮后显示。 如果我不点击按钮,表格应该是隐藏的。

提前感谢您的回复。

【问题讨论】:

    标签: java jquery ajax


    【解决方案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 的简化且性能更高。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-18
      • 1970-01-01
      • 1970-01-01
      • 2020-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-06
      相关资源
      最近更新 更多