首页 > 解决方案 > 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/>' 显示为字符串)。

有人可以解释一下吗?

标签: jqueryhtmlejs

解决方案


这不是 jQuery 的html功能,而是 EJS,它会自动转义您的<%= ... %>表达式产生的文本。

在您的第二个示例中,如果您在attachmentFileNames调试器中查看 的值,您可能会看到&lt;br/>(or &lt;br/&gt;) 而不是<br/>. 当您将"&lt;br/>"(或"&lt;br/&gt;") 用作 HTML 时,结果是字符<br/>

const attachmentFileNames1 = 'one,two';
if (attachmentFileNames1) {
    $("#attachmentFileNameList1").html(attachmentFileNames1.replace(',', '<br/>'));
}

const attachmentFileNames2 = 'one&lt;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>


推荐阅读