引言:以前做毕计突然碰上onclick传动态值失效的问题,开始写的是这个语句,在管理页面可以实现没有问题。
th:onclick="'javascript:_queryPage(\''+${动态值}+'\')'"
- 动态值:${item.属性名} 以上方法在标签一直报错没有反应,前端查看就变成了这样了:
onclick="javascript:_queryPage(1,‘属性值’)"
单击事件直接失效了。一直报错 org.thymeleaf.exceptions.TemplateProcessingException: Only variable expressions returning numbers or booleans are allowed in this context, any other datatypes are not trusted in the context of this expression, including Strings or any other object that could be rendered as a text literal. A typical case is HTML attributes for event handlers (e.g. "onload"), in which textual data from variables should better be output to "data-*" attributes and then read from the event handler. 解决办法: 此方法对我来说解决了,如果碰上这个问题可以参考一下:
<a href="javascript:void(0)" th:text="${item.name}"
th:data-id ="${item.code}"
onclick="_queryPage(1,this.getAttribute('data-id'))"></a>
上面的th:data-* = "${动态值}" onclick里面就可以直接用this.getAttribute('data-*')取值就行,我的问题解决了,前台解析显示: onclick="_queryPage(1,this.getAttribute('data-id'))"可以解决。
其他解决办法(仅供参考):
- 方法一:
th:onclick="function([[${param}]])"
- 方法二(和我最开始用的方法一样):
<button th:onclick="'javascript:del(\''+${item.id}+'\');'" type="button"></button>
- 方法三(这个方法有可能报错,我开始用的时候一直不行,但是我看有的人就好使):
<a href="#" th:onclick="'javascript:updateState([[#{item.id}]],2);'" title="删除"><i class="fa fa-edit text-navy"></i></a>
- 方法四(没有使用)
<button th:onclick="|getName(${person.name} )|">获得名字</button>
<button class="btn" th:onclick="'getName(' + ${person.name} + ');'">获得名字</button>
- 最终方法 检查是否是代码书写错误,或者后台传值问题。还有其他方法请补充,以上都是我踩的坑。