开发者

Javascript String argument with character reference

I have a javascript method call with a string parameter. In the string text sometimes contains html character references, e.g. ' I am getting an unexpected identifier error. If I have the character reference as " then it works fine. Not sure why that is. Below is a code snippet of what I am trying to do. Actual method is much longer and trying to do something different than what I show here, but this snippet should be able to reproduce the error.

<script>
function unescapeHTML(html) {
  var htmlNode = document.createElement("div");
  htmlNode.innerHTML = html;
  if(htmlNode.innerText)
    alert htmlNode.innerText; // IE
  else 
   开发者_如何学编程 alert htmlNode.textContent; // FF

}
</script>
<a class="as_Glossary" onmouseover="unescapeHTML('The manufacturer&#39;s sales in dollars to all purchasers in the United States excluding certain exemptions for a specific drug in a single calendar quarter divided by the total number of units of the drug sold by the manufacturer in that quarter'); return true;" onmouseout="hideGlossary(); return true;">Test</a>

When I mouseover I get the error


The issue is that your &#39; is being converted to a ' before the JavaScript is evaluated. So, JavaScript sees the following (wrapped for readability):

unescapeHTML('The manufacturer's sales in dollars to all purchasers in 
the United States excluding certain exemptions for a specific drug in a 
single calendar quarter divided by the total number of units of the drug 
sold by the manufacturer in that quarter'); 
return true;

Notice how the string ends after manufacturer, and the rest is treaded as code, with an extra unmatched close quote '. You need to prefix the ' in manufacturer's with a backslash in order for the string to be properly quoted in JavaScript:

a class="as_Glossary" onmouseover="unescapeHTML('The manufacturer\&#39;s sales...

You also need parentheses in your alert expressions:

function unescapeHTML(html) {
  var htmlNode = document.createElement("div");
  htmlNode.innerHTML = html;
  if(htmlNode.innerText)
    alert(htmlNode.innerText); // IE
  else 
    alert(htmlNode.textContent); // FF
}


You need a semi-colon after that character reference

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜