首页 > 解决方案 > Thymeleaf 表格行点击不识别 js 功能

问题描述

onclick 事件抱怨未定义 java 脚本函数。

<body>
    <div layout:fragment="content" th:remove="tag">
        <div class="container">
            <h6 class="mb-3">Restaurant Order Details</h6>
            <table class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th scope="col">Order Id</th>
                        <th scope="col">Order Details</th>
                        <th scope="col">Date</th>
                        <th scope="col">Amount</th>
                    </tr>
                </thead>
                <tbody>

                    <tr th:each="order : ${orders}" style="cursor: pointer"
                        th:attr="onclick=|getOrderItems('${order.orderId}')|">
                        <td scope="row" th:text="${order.orderId}"></td>
                        <td th:text="${order.orderDetais}"></td>
                        <td th:text="${order.orderDate}"></td>
                        <td th:text="${order.amount}"></td>
                    </tr>
                    <tr>
                        <td colspan="3">Total</td>
                        <td th:text="${grandTotal}"></td>
                    </tr>
                </tbody>
            </table>
            <div class="mb-4"></div>


        </div>
    </div>
    <script>
        function getOrderItems(orderId) {
            alert("order details here");
        }
    </script>
</body>

当我点击表格行时,我得到

Uncaught ReferenceError: getOrderItems is not defined
    at HTMLTableRowElement.onclick

当我用简单的警报替换 getOrderItems 时,会触发警报。我该如何解决?

标签: springthymeleaf

解决方案


这里的问题是我在标签<script> 之外声明了我的。<div layout:fragment="content" th:remove="tag">由于这是一个片段,因此 thymeleaf 仅渲染此范围内的所有内容。将脚本标签放在其中解决了这个问题。


推荐阅读