使用jQuery.attr()转义属性值 [英] Escaping of attribute values using jQuery.attr()
问题描述
当使用jQuery更新元素的 title
属性时,我发现实体(特别是

,这是目前推荐的在 title
属性中添加换行符的方式)无法正确显示(实体显示为文本并且未解析...) 。
例如:
<! - This works好 - >
< div title =foo&#10; bar> baz< / div>
但是:
< DIV>巴兹< / DIV>
< script>
$(div)。attr('title','foo&#10; bar'); //退出&
< / script>
有没有办法让jQuery没有这个值?我尝试在 .attr()
之前使用 unescape()
,但它不起作用...
你是对的; unescape()
在这种情况下不起作用。你可以做的是类似于答案中提到的东西
基本上,使用jQuery创建一个空元素,在标题中设置它为HTML所需的文本('foo&#10; bar'
),然后找回元素的文本。它是,但是这将适用于任何HTML实体,它实际上只是一个单线程。代码如下:
< div> baz< / div>
< script>
var title = $('< div />')。html('foo&#10; bar')。text();
$(div)。attr('title',title);
< / script>
或者在一行上:
<$ p $ ('foo&#10; bar')。text()); $('div')。attr('title',$('< div />')。
When using jQuery to update the title
attribute of an element, I find that the entities (notably
, which is the currently recommended way of adding line breaks in the title
attribute) do not display correctly (the entity shows up as text, and is not parsed…).
For example:
<!-- This works fine -->
<div title="foo bar">baz</div>
But this:
<div>baz</div>
<script>
$("div").attr('title', 'foo bar'); // Escapes the &
</script>
Is there a way to not have jQuery escape the value? I tried using unescape()
before .attr()
, but it didn't work…
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 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 bar').text();
$("div").attr('title', title);
</script>
Or on one line:
$('div').attr('title', $('<div/>').html('foo bar').text());
这篇关于使用jQuery.attr()转义属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!