我是 thymeleaf 的新手。现在,我在使用 thymeleaf 时遇到了一个简单的问题。实际上,我必须调用这样的 Javascript 函数,
<input type="button" onclick="function1('myvariable')">
我已将值存储在属性名为“attr”的模型中。访问时我尝试了类似这样的代码,
<input type="button" th:onclick="${'function1('+attr+')'">
现在这里出现的问题是我无法执行 onclick 函数,因为 onclick 中的值是
<input type="button" onclick="function1(myvariable)">
它给出了一个Javascript错误“myvariable”未定义。一旦符号单引号进入函数1,它就会得到解决。我不知道该怎么做。任何人都可以帮助我吗?
最佳答案
您只需使用 \'
转义文字中的单个逗号即可:
<input type="button" th:onclick="${'function1(\''+attr+'\')'">
根据 StackOverflow 规则免责声明:我是 thymeleaf 的作者。
更新:如果使用 Spring EL,则应该是:
<input type="button" th:onclick="${'function1('''+attr+'''')'">
关于java - 在 thymeleaf 中调用函数时将模型值作为字符串类型包含在内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22042855/