thymeleaf中th:onclick如何进行参数值的传递

在Thymeleaf中使用th:onclick传递参数时,如果你遇到了错误信息“Only variable expressions returning numbers or booleans are allowed in this context”,你可以通过以下方法来解决这个问题:

方法1:使用双括号[[...]]来传递字符串参数

当你需要传递字符串类型的参数时,可以使用双括号[[...]]来确保参数被正确地传递给JavaScript函数。例如:
<button th:onclick="handleToMore([[${page}]], [[${limit}]])">Load More</button>

在这个例子中,${page}${limit}是Thymeleaf变量,它们会被替换为实际的值,并且这些值会被传递给handleToMore函数。

方法2:使用data-*属性传递参数

另一种方法是将参数存储在data-*属性中,然后在JavaScript中读取这些属性。例如:
<button th:data-page="${page}" th:data-limit="${limit}" th:onclick="handleToMore(this)">Load More</button>

然后在JavaScript中,你可以通过this关键字访问当前元素,并获取data-pagedata-limit属性的值:

function handleToMore(button) {
    var page = button.getAttribute('data-page');
    var limit = button.getAttribute('data-limit');
    // 你的逻辑代码
}
这种方法可以避免直接在th:onclick中拼接字符串,从而减少潜在的安全风险。通过以上方法,你可以有效地在Thymeleaf中使用th:onclick传递参数,同时避免常见的错误信息。
posted @ 2025-01-09 17:09  子墨老师  阅读(648)  评论(0)    收藏  举报