使用 JS 设置 HTML "title" 属性不会呈现 &

Setting HTML "title" attribute with JS doesn't render &

在标题属性中使用符号的正确方法是什么?我会假设你应该使用 &,但它会根据它是在原始 HTML 中设置还是用 JS 修改而给出不同的行为。

Chrome(版本 47.0.2526.106(64 位))和 Safari(版本 9.0.2 (11601.3.9))中的工具提示呈现:

https://jsfiddle.net/davegaeddert/femm9b96/

根据您的设置方法不同。在原始 HTML 中,您必须转义与号,而您的 fiddle 正在正确执行此操作:

title="&"

在JavaScript中,你可以只在字符串中使用"&"

jQuery("#with-js").attr("title","&");

& 表示 & 在 HTML.

当您使用 DOM API 直接操纵 DOM 时,

& 表示 &

如果您不编写 HTML,请不要使用 HTML 个实体。

那是因为 setAttribute 不会将属性解析为 HTML。请参阅 Node.setAttribute

的规范

当直接在 HTML 中时,它将被解析为 HTML 个实体

节选

This value is a simple string; it is not parsed as it is being set. So any markup (such as syntax to be recognized as an entity reference) is treated as literal text

https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-F68F082