Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

javascript - Escaping of attribute values using jQuery.attr()

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&#10;bar">baz</div>

But this:

<div>baz</div>
<script>
$("div").attr('title', 'foo&#10;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…

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

jQuery isn't escaping anything, in fact your string is literally set as the title. You can simply use:

$("div").attr('title','foo
bar')

http://jsfiddle.net/t5DvY/


There seems to be a whole lot of misunderstanding what escaping means. What you are doing is completely unnecessary.

Escaping is only necessary in a context where the character would otherwise have a special meaning and you want it not to have any special meaning.

For example, in the eyes of html parser, < is special. You have to replace it with &lt; if you want to ensure it is treated as literal <. Emphasis on in the eyes of html parser. In javascript, < is not special in a string in any way, thus you could do elem.setAttribute("title", '""><b>hi</b>') and that's what you get, the element's title will literally be ""><b>hi</b>.

As for html code point references, they are generally useless. You can simply use literal characters. Instead of writing &#x2665;, you can simply write ?. Instead of writing &#x00F6;, you can simply write ?. Here's http://jsfiddle.net/fnqDn/2/.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...