简体   繁体   English

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

[英]Setting HTML “title” attribute with JS doesn't render &

What is the proper way to use an ampersand in the title attribute? 在title属性中使用&符号的正确方法是什么? I would have assumed that you should use & 我原以为你应该使用& , but it gives different behavior depending on whether it was set in the original HTML or modified with JS. ,但它会提供不同的行为,具体取决于它是在原始HTML中设置还是使用JS修改。

Tooltip rendering in Chrome (Version 47.0.2526.106 (64-bit)) and Safari (Version 9.0.2 (11601.3.9)): Chrome(版本47.0.2526.106(64位))和Safari(版本9.0.2(11601.3.9))中的工具提示渲染:

在此输入图像描述 用JS

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

& means & in HTML . 表示& 在HTML中

& means & 手段& when you are directly manipulating the DOM using a DOM API. 当您使用DOM API直接操作DOM时。

If you aren't writing HTML, don't use HTML entities. 如果您不编写HTML,请不要使用HTML实体。

The method is different depending on how you set it. 根据您的设置方式,该方法会有所不同。 In raw HTML, you have to escape the ampersand, and your fiddle is doing it correctly: 在原始HTML中,你必须逃避&符号,你的小提琴正确地做到了:

title="&"

In JavaScript, you can just use "&" in a string: 在JavaScript中,您只需在字符串中使用"&"

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

That's because setAttribute does not parse attributes as HTML. 那是因为setAttribute不会将属性解析为HTML。 See the specification for Node.setAttribute 请参阅Node.setAttribute的规范

When directly in the HTML, it will be parsed for HTML entities 直接在HTML中,它将被解析为HTML实体

Excerpt 摘抄

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 https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-F68F082

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM