thymeleaf - Thymeleaf 对 onmouseover 处理程序的限制
问题描述
我正在翻译一个古老的 Struts/JSP 应用程序以使用 Spring 5 和 Thymeleaf。原始应用程序在表中的行的变量 tt 上有一个 logic:iterate 标记,并且单元格显示在后端格式化为用户时区的时间戳,悬停在 UTC 上,如下所示:
<td style="cursor: pointer; cursor: hand"
onmouseover="return escape('<bean:write name="tt" property="ts_UTC" />' + ' UTC')">
<bean:write name="tt" property="ts_User" /></td>
它生成如下所示的输出:
<td style="cursor: pointer; cursor: hand"
onmouseover="return escape('04/06/2020 11:14:50 AM' + ' UTC')">
04/06/2020 07:14:50 AM</td>
经过几次尝试并阅读https://github.com/thymeleaf/thymeleaf/issues/705和https://github.com/thymeleaf/thymeleaf/issues/707后,我将其翻译为 thymeleaf,如下所示:
<td style="cursor: pointer; cursor: hand"
th:onmouseover="return escape( '[[${tt.ts_UTC}]] UTC');"
th:text="${tt.ts_user}"></td>
问题是生成的输出如下所示:
<td style="cursor: pointer; cursor: hand"
onmouseover="return escape( '"05\/04\/2015 08:05:24 PM" UTC');"
>05/04/2015 04:05:24 PM</td>
我不知道“”在哪里 来自,我真的希望 ' 变回撇号。我难住了。我该怎么做呢?
解决方案
我不知道这是否是一个完整的解决方案 - 因为我不知道鼠标悬停事件最终如何显示文本。但...
我建议将事件处理程序移到一个单独的 JavaScript 函数中,以使事情更干净、更灵活。
从这个开始:
<div style="cursor: pointer; cursor: hand"
th:onmouseover="showMouseoverText( /*[[${tt.ts_UTC}]]*/ );"
th:text="${tt.ts_user}">
</div>
那是在/*[[${tt.ts_UTC}]]*/
做什么?它使用JavaScript 内联的转义形式- 双括号表示法。但它也将其包装在注释中,这利用了 Thymeleaf 的JavaScript 自然模板。这确保在处理模板时没有语法错误。
然后在你的<head>...</head>
部分的某个地方,添加这个:
<script th:inline="javascript">
function showMouseoverText( ts ) {
console.log(ts + ' UTC');
return escape(ts + ' UTC');
}
</script>
控制台线只是为了测试。对我来说,我的静态测试数据打印如下:
04/06/2020 11:14:50 AM UTC
我不知道最后一行return escape(ts + ' UTC')
是否会按您需要的方式工作。我不确定它的作用。
您在 HTML 页面中获得的内容如下:
分区:
<div style="cursor: pointer; cursor: hand"
onmouseover="showMouseoverText( "04\/06\/2020 11:14:50 AM");">John Doe
</div>
您将看到转义/
字符和表示为的单引号"
。但是 JavaScript 函数应该处理这些(如上面的控制台输出所示)。如果没有,那么至少您可以根据需要操作函数中的数据。
推荐阅读
- flutter - 水平滚动周历颤动
- android - 将 Laravel APP 转换为 Apache Cordova APP
- spring-integration - Spring Integration - 重放相同的流程
- react-admin - React-admin:使用 CloneButton 时如何省略创建视图?
- swift - 如何从选择突出显示不同颜色的折线图
- javascript - 按钮编辑更改数据属性以输入
- intersystems-iris - 类日期/时间属性有什么用
- grafana - Grafana:即使“警报验证错误:未找到警报规则使用的数据源”,也会加载仪表板
- ethereum - ERC20 代币转移到智能合约
- mysql - 函数中有哪些功能,但存储过程中没有?