11

在使用 jQuery 更新title元素的属性时,我发现实体(特别是
,这是目前推荐的在属性中添加换行符的方式title)无法正确显示(实体显示为文本,并且未解析... )。

例如:

<!-- This works fine -->
<div title="foo&#10;bar">baz</div>

但是这个:

<div>baz</div>
<script>
$("div").attr('title', 'foo&#10;bar'); // Escapes the &
</script>

有没有办法让 jQuery 不转义值?unescape()我之前试过用.attr(),但是没用……</p>

4

4 回答 4

17
于 2012-07-21T10:01:57.543 回答
15

You are right; unescape() will not work in this case. What you can do is something similar to what is mentioned in the answer here.

Basically, create an empty element using jQuery, set it's HTML to the text you want in the title ('foo&#10;bar' in this case) and then get back the element's text.

Sounds a little complicated? It is, but this will work for any HTML entity and it's really just a one-liner. Here's the code:

<div>baz</div>
<script>
    var title = $('<div/>').html('foo&#10;bar').text();
    $("div").attr('title', title);
</script>

Or on one line:

$('div').attr('title', $('<div/>').html('foo&#10;bar').text());
于 2012-07-21T10:08:58.237 回答
5

This function will save you time, if you'll be doing this a lot:

function unescp(x){
 return $('<div/>').html(x).text();
}
$("div").attr('title',unescp('foo&#10;bar'));

See it here: http://jsfiddle.net/9Lnru/ ​</p>

于 2012-07-21T10:14:59.720 回答
0

您可以尝试将值放在隐藏元素中。并让 jquery 将该值复制到 div。我不确定它是否会通过 jQuery 被忽视,但值得一试......

于 2012-07-21T10:00:21.107 回答