Bootstrap 莫代尔 window 和 Thymeleaf

Bootstrap Modal window and Thymeleaf

我有一个使用 Spring Mvc 的项目,我想使用 Bootstrap 模态 windows 和 Thymeleaf。当我在没有 Thymeleaf 的情况下进行循环时,我有一个视图 students.jsp 从模型中获取学生列表一切正常。 我用JS。但是当我使用 Thymeleaf 模型时 windows 没有正常工作。

    <table class="table table-hover">
        <thead>
            <tr>
                <th>Firstname</th>
                <th>Lastname</th>
                <th>Email</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
                <tr id="user-${user.id}" th:each="user: ${students}">

                    <td th:text="${user.id}" />
                    <td th:text="${user.firstName}" />
                    <td th:text="${user.lastName}" />
                    <td>
                        <button type="button" class="btn btn-primary editButton"
                            data-toggle="modal" data-target="#myModal" data-user-id="${user.id}">Edit</button>
                    </td>
                </tr>
        </tbody>
    </table>
    <script type="text/javascript">
        $("#myModal").on('show.bs.modal', function(e) {
            var userId = $(e.relatedTarget).data('user-id');

            var cols = $('#user-' + userId + ' td');
            var firstName = $(cols[0]).text();
            var lastName = $(cols[1]).text();
            var email = $(cols[2]).text();

            $('#firstNameInput').val(firstName);
            $('#lastNameInput').val(lastName);
            $('#emailInput').val(email);
        });

        $("#myModal").on('hidden.bs.modal', function() {
            var form = $(this).find('form');
            form[0].reset();
        });
    </script>

它没有从列表中获取数据。我不知道如何解决这个问题。请帮助我:)

您的“编辑”按钮中的 data-user-id 属性存在一个小问题。

而不是:

data-user-id="${user.id}"

...你应该有:

th:data-user-id="${user.id}"

...以便属性由 Thymeleaf 处理并且 ${user.id} 实际上替换为预期值。

<tr th:each="user: ${students}" th:id="'user-' + ${user.id}">
                <td th:text="${user.id}" />
                <td th:text="${user.firstName}" />
                <td th:text="${user.lastName}" />
                <td th:text="${user.email}" />
                <td>
                    <button type="button" class="btn btn-primary editButton"
                        data-toggle="modal" data-target="#myModal"
                        th:data-user-id="${user.id}">Edit</button>
                </td>
            </tr>