why can't I set an ascii reference in an img t

2019-07-23 16:56发布

问题:

I'm having trouble using an ascii character reference (®) in an image title. It works fine when you set it via the html body, but when trying to do the same thing via javascript does not work.

check the sscce:

<style type="text/css">body {background-color:black;}</style>
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<p>this image has the correct ascii character title:<br /><img src="http://www.prototypejs.org/images/logo-home.gif" id="img1" title="&reg;" /></p>
<p>but why can't I set the same value via javascript?<br /><img src="http://www.prototypejs.org/images/logo-home.gif" id="img2" /></p>
<script type="text/javascript">
$("img2").title = "&reg;";
</script>

Thanks.

回答1:

$("img2").title = "®" should work, if not use

$("img2").title ='\u00AE'.

The html entities are not translated for pure text.



回答2:

There are a wealth of answers at http://paulschreiber.com/blog/2008/09/20/javascript-how-to-unescape-html-entities/

But basic gist of it is your setting the text of the node not the html, so there are no html entities.

You can however set the innerHTML of a hidden object and read the text value of that. Or assuming your source encoding allows it just enter the reg symbol directly.