简体   繁体   English

在 Thymeleaf th:each 中使用 JavaScript 变量

[英]Using JavaScript variables in a Thymeleaf th:each

I am trying to build a table using th:each and have the whole row of the table clickable as a link through JavaScript.我正在尝试使用 th:each 构建一个表,并通过 JavaScript 将表的整行作为链接单击。

<table>
    <th:block th:each='user : ${list}'>
        <script th:inline="javascript">
            var userid = [[${user.id}]];
        </script>
        <tr onclick="location.href='user?id='+userid">
            <td th:text="${user.firstName}"></td>
            <td th:text="${user.lastName}"></td>    
        </tr>
    </th:block>
</table>

However, the variable always refers to the latest value and not the one it was when the row was created.但是,该变量始终引用最新值,而不是创建行时的值。 Is there a way to do that?有没有办法做到这一点? Or maybe a different solution to what I'm trying to do?或者也许是我想要做的不同的解决方案?

You need to change your design,你需要改变你的设计,

The reason is: we can not use client variable in server side,but we can use server variable in client side原因是:我们不能在服务器端使用客户端变量,但我们可以在客户端使用服务器变量

Because when we compile thymeleaf code in server side we do not know which client will access it,so it can not assign value to the specific client因为当我们在服务器端编译thymeleaf代码时,我们不知道哪个客户端会访问它,所以它不能为特定的客户端赋值

You can avoid using JavaScript by adding an <a> element to each table cell (Inspired by https://stackoverflow.com/a/17147909/40064 ):您可以通过向每个表格单元格添加一个<a>元素来避免使用 JavaScript(受https://stackoverflow.com/a/17147909/40064启发):

<table>
    <th:block th:each='user : ${list}'>
        <tr>
            <td><a th:href="@{/user(id=${userid})}" th:text="${user.firstName}"></a></td>
            <td><a th:href="@{/user(id=${userid})}" th:text="${user.lastName}"></a></td>    
        </tr>
    </th:block>
</table>

No need for the th:block , you can simply put the th:each on the tr .不需要th:block ,您可以简单地将th:each放在tr上。

To accomplish the click, I recommend putting the id in a data attribute, and retrieving it in JavaScript.要完成点击,我建议将 id 放在data属性中,然后在 JavaScript 中检索它。 This should work for you:这应该适合你:

<table>
    <tr th:each="user : ${list}"
        th:data-id="${user.id}"
        onclick="location.href = 'user?id='+this.getAttribute('data-id')">
        <td th:text="${user.firstName}"></td>
        <td th:text="${user.lastName}"></td>    
    </tr>
</table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM