带有字符引用的 Javascript 字符串参数
我有一个带有字符串参数的 JavaScript 方法调用。在字符串文本中有时包含 html 字符引用,例如 '
我收到意外的标识符错误。如果我的字符引用为 "
那么它就可以正常工作。不知道为什么会这样。下面是我正在尝试做的事情的代码片段。实际方法要长得多,并且尝试做一些与我在这里展示的不同的事情,但是这个片段应该能够重现错误。
<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'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>
当我将鼠标悬停时出现错误
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'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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您的
'
在 JavaScript 被评估之前被转换为'
。因此,JavaScript 会看到以下内容(为了便于阅读而进行了包装):注意字符串如何在
manufacturer
之后结束,其余部分将作为代码处理,并带有额外的不匹配的闭引号'
。您需要在manufacturer's
中的'
前面加上反斜杠,以便在 JavaScript 中正确引用该字符串:您还需要在
alert
表达式:The issue is that your
'
is being converted to a'
before the JavaScript is evaluated. So, JavaScript sees the following (wrapped for readability):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'
inmanufacturer's
with a backslash in order for the string to be properly quoted in JavaScript:You also need parentheses in your
alert
expressions:在该字符引用后需要一个分号
You need a semi-colon after that character reference