jQuery的attr()函数用html特殊字符打破html? [英] jQuery's attr() function breaks html with html special characters?

查看:100
本文介绍了jQuery的attr()函数用html特殊字符打破html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看以下代码:

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

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

In the first link there is a title attribute containing the html special character &lt; followed by "!" (it doesn't matter which character it is followed by actually). When we take the value of that title attribute with jQuery's attr() function the html is broken (you can see that there is no "<" character printed as long as the following text is also missing.

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

In the second link the only difference is that I have added a space after &lt; and now it works as expected.

您认为这是jQuery中的错误还是我不明白?

Do you think it's a bug in jQuery or I just don't understand something?

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

PS. If you think I'm doing something strange - it's just some piece of code from some tooltip plugin.

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 属性和引用说:

This is pretty interesting. I looked up what text can be in a title attribute and the reference says:


用户代理应解释属性值,如下所示:

User agents should interpret attribute values as follows:


  1. 用字符替换字符实体

  2. 忽略换行,

  3. 用一个空格替换每个回车或标签。


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

Apparently, this is the expected behavior. &lt; is being parsed as < by the browser, which might be interpreted as HTML by jQuery.

你也应该逃避&符号:

&amp;lt;

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

Demo: http://jsfiddle.net/htdTg/9/

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

Even better demo: http://jsfiddle.net/PsZeY/6/

这篇关于jQuery的attr()函数用html特殊字符打破html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆