<table border="1">
<tr>
<td>名字td>
<td>价格td>
<td>单价td>
<td>操作td>
tr>
<tr th:each="info:${page}">
<td th:text="${info.type}">名字td>
<td th:text="${info.price}">价格td>
<td th:text="${info.dates}">天数td>
<td>
<a href="javascript: void(0) " th:href="@{/delete/}+${info.id}" >删除1a>
<a href="javascript: void(0) " th:onclick="confirmDel(${page})" >删除2a>
<a href="javascript:void (0)" th:href="@{/gotoEdit(id=${info.id})}">修改a>
td>
tr>
table>
终于解决了,这里面还隐藏着另一个坑,那就是无法传字符串类型的值,而我的type就是字符串,查了日志才发现这个问题。我用data-icon拼接id和type的值,confirmDel()拿到值后在根据逗号(,)分割,就可以做到获取id和type的值,谢谢大家帮忙,感谢!
<button th:data-icon="|${info.id},${info.type}|"
onclick="confirmDel(this.getAttribute('data-icon'))" >删除3</button>
这个问题是由于你在使用 thymeleaf 模板引擎来渲染 HTML 页面,而 thymeleaf 模板引擎会在运行时替换掉 th: 开头的属性值,导致 th:onclick 的值无法正确传递给 JavaScript 代码。
解决方案是在 HTML 页面中直接定义 JavaScript 代码,并在需要调用的地方调用该函数即可。
举个例子,你可以在 HTML 页面的 head 标签中定义一个 JavaScript 函数,如下所示:
<script type="text/javascript">
function confirmDel(info) {
var type = info.type;
var id = info.id;
if (confirm("确定要删除品类为 " + type + " 的记录吗?")) {
// 在这里发送 AJAX 请求删除数据
}
}
</script>
然后在你的 HTML 页面中的删除按钮上调用该函数,如下所示:
<a href="javascript:void(0)" onclick="confirmDel({{info}})">删除2</a>
这样就能正确获取变量了。