javascript - jQuery 的 attr() 函数用 html 特殊字符破坏 html?

标签 javascript jquery html

请看下面的代码:

http://jsfiddle.net/htdTg/2/

在第一个链接中有一个 title 属性包含 html 特殊字符 < 后跟“!” (实际上后面跟着哪个字符并不重要)。 当我们使用 jQuery 的 attr() 函数获取该 title 属性的值时,html 被破坏了(您可以看到,只要下面的文本也丢失,就没有打印“<”字符。

在第二个链接中,唯一的区别是我在 < 之后添加了一个空格,现在它按预期工作了。

您认为这是 jQuery 中的错误还是我只是不明白某些东西?

附言。如果您认为我在做一些奇怪的事情 - 它只是来自某个工具提示插件的一段代码。

HTML:

<a href="#" title="<div style='color:red'>This is the less than sign: &lt;! Now you know it?</div>">This is a link</a><br>
<a href="#" title="<div style='color:red'>This is the less than sign: &lt; ! 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: &lt;! Now you know it?</div>");​

最佳答案

这很有趣。我查找了 title attribute 中可以包含哪些文本引用文献说:

User agents should interpret attribute values as follows:

  1. Replace character entities with characters,
  2. Ignore line feeds,
  3. Replace each carriage return or tab with a single space.

显然,这是预期的行为。 &lt;被解析为 <由浏览器,它可能被 jQuery 解释为 HTML。

你也应该转义符号:

&amp;lt;

演示:http://jsfiddle.net/htdTg/9/

更好的演示:http://jsfiddle.net/PsZeY/6/

关于javascript - jQuery 的 attr() 函数用 html 特殊字符破坏 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13847485/

相关文章:

html - 自动缩放背景图像

javascript - 使用 javascript 对象作为 "function store"并动态调用它们?

javascript - 使用 javascript 的 call() 理解链式构造函数

javascript - 在javascript中转换对象类型?

javascript - 如何使用属性来获取 JSON 值?

jquery - 在更改纵横比的同时使用百分比值调整图像大小

javascript - 三星智能电视应用程序带场景和不带场景的区别?

javascript - Django:在表单提交上发出 POST 请求而不重新加载页面或渲染到另一个页面?

javascript - JSON 对象数组,用于在本地临时存储中存储表单数据(PhoneGap 项目)

python - lxml - 如何获取 HtmlElement 的 xpath?