簡體   English   中英

如何通過單擊按鈕隱藏和顯示表格?

[英]How to hide and show table by click on button?

這是我的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 :即使我沒有單擊按鈕Groups ,組 ID 和組名也在頁面上,但我需要我的表僅在單擊按鈕后顯示。 如果我不點擊按鈕,表格應該被隱藏。

提前感謝您的回復。

我需要我的表格僅在單擊按鈕后顯示。 如果我不點擊按鈕,表格應該被隱藏。

在這種情況下,使用 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 的簡化且性能更高。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM