Javascript 双引号内单引号的字符串问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5947355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:54:10  来源:igfitidea点击:

String problems with Javascript double quotes inside single

javascriptstring

提问by fire

This is my code:

这是我的代码:

<script>
    function popupTest(title) {
        alert(title);
        return false;
    }
</script>

<a href="" onclick="return popupTest('This is &#039;some&#039; &quot;test&quot; string')"><span>Recommend</span></a>

Using Firefox 4 I get the error:

使用 Firefox 4 我收到错误:

Error: missing ) after argument list
Source Code:
return popupTest('This is 'some' "test" string')

It's like it's decoding the HTML entities but I don't know why.

就像它正在解码 HTML 实体,但我不知道为什么。

Have also tried...

也试过...

<a href="" onclick="return popupTest('This is \'some\' \"test\" string')"><span>Recommend</span></a>

Which gives error:

这给出了错误:

Error: unterminated string literal
Source Code:
return popupTest('This is \'some\' \

回答by Quentin

&#039;is HTMLfor '. So for the first example the HTML is parsed and the JavaScript engine is passed:

&#039;HTML'. 因此,对于第一个示例,解析 HTML 并传递 JavaScript 引擎:

return popupTest('This is 'some' "test" string')

… and the second 'terminates the string.

… 第二个'终止字符串。

On the other hand:

另一方面:

onclick="return popupTest('This is \'some\' \"test\" string')"

Is parsed as:

被解析为:

An onclick attribute with the value return popupTest('This is \'some\' \followed by some invalid data.

带有值return popupTest('This is \'some\' \后跟一些无效数据的 onclick 属性。

You need to deal with the JavaScript first:

您需要先处理 JavaScript:

return popupTest('This is \'some\' "test" string')

andthen escape it for HTML:

并且,然后逃逸它的HTML:

onclick="return popupTest('This is \'some\' &quot;test&quot; string')"

You would probably be better off using unobtrusive JavaScriptand binding the event handlers with JavaScript instead of using intrinsic event attributes.

您可能最好使用不引人注目的 JavaScript并使用JavaScript绑定事件处理程序,而不是使用内部事件属性。