jquery - jQuery 的 .html() 如何处理 JavaScript 字符串?
问题描述
我有快速应用程序和 EJS 作为视图引擎。我正在尝试以两种不同的方式将一些 html 设置为 div:
const attachmentFileNames = '<%= eco.attachmentFileName %>';
if (attachmentFileNames) {
$("#attachmentFileNameList").html(attachmentFileNames.replace(',', '<br/>'));
}
和
const attachmentFileNames = "<%= eco.attachmentFileName ? eco.attachmentFileName.replace(',', '<br/>') : '' %>";
if (attachmentFileNames) {
$("#attachmentFileNameList").html(attachmentFileNames);
}
问题是代码的第一个和平按预期工作('<br/>' 被视为行终止符),但第二个只是将所有数据设置为文本('<br/>' 显示为字符串)。
有人可以解释一下吗?
解决方案
这不是 jQuery 的html
功能,而是 EJS,它会自动转义您的<%= ... %>
表达式产生的文本。
在您的第二个示例中,如果您在attachmentFileNames
调试器中查看 的值,您可能会看到<br/>
(or <br/>
) 而不是<br/>
. 当您将"<br/>"
(或"<br/>"
) 用作 HTML 时,结果是字符<
、b
、r
、/
和>
:
const attachmentFileNames1 = 'one,two';
if (attachmentFileNames1) {
$("#attachmentFileNameList1").html(attachmentFileNames1.replace(',', '<br/>'));
}
const attachmentFileNames2 = 'one<br/>two';
if (attachmentFileNames2) {
$("#attachmentFileNameList2").html(attachmentFileNames2);
}
<div id="attachmentFileNameList1"></div>
<div id="attachmentFileNameList2"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
推荐阅读
- ruby-on-rails - rails 从具有相似功能的两个独立模型中获取列表
- java - 在 Java 中加载资源时出现奇怪的问题
- c++ - 如何降低我的(非正统的)基于 Qt5/QML 的软件的内存使用量?
- functional-programming - 调用函数和函数式编程有什么区别
- c# - C# 编译表达式以创建 T 的新实例并将值从 T 的另一个实例复制到其属性
- c# - 如何修复 'IHasInputDevices 已过时。使用 Actions 或 ActionsBuilder 类通过 Selenium 模拟鼠标和键盘输入警告
- node.js - 其他 IPS 无法访问 NodeJS 项目
- swift - 转换到视图控制器时强制解开 UIImageView 的 nil 可选
- jquery - 为 DT 闪亮中的单列渲染下拉列表,但仅在单元格单击和 replaceData() 时加载
- oauth-2.0 - 在 WSO2 身份服务器中使用 JWT 授予添加声明以访问令牌