请看下面的代码:
在第一个链接中有一个 title 属性包含 html 特殊字符 <
后跟“!” (实际上后面跟着哪个字符并不重要)。
当我们使用 jQuery 的 attr() 函数获取该 title 属性的值时,html 被破坏了(您可以看到,只要下面的文本也丢失,就没有打印“<”字符。
在第二个链接中,唯一的区别是我在 <
之后添加了一个空格,现在它按预期工作了。
您认为这是 jQuery 中的错误还是我只是不明白某些东西?
附言。如果您认为我在做一些奇怪的事情 - 它只是来自某个工具提示插件的一段代码。
HTML:
<a href="#" title="<div style='color:red'>This is the less than sign: <! Now you know it?</div>">This is a link</a><br>
<a href="#" title="<div style='color:red'>This is the less than sign: < ! Now you know it?</div>">This is a link</a><br>
jQuery:
$('a').each(function() {
$('body').append($(this).attr('title')); });
// just to exclude that it's append() function's fault :)
$('body').append("<div style='color:red'>This is the less than sign: <! Now you know it?</div>");
最佳答案
这很有趣。我查找了 title
attribute 中可以包含哪些文本引用文献说:
User agents should interpret attribute values as follows:
- Replace character entities with characters,
- Ignore line feeds,
- Replace each carriage return or tab with a single space.
显然,这是预期的行为。 <
被解析为 <
由浏览器,它可能被 jQuery 解释为 HTML。
你也应该转义符号:
&lt;
关于javascript - jQuery 的 attr() 函数用 html 特殊字符破坏 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13847485/