繁体   English   中英

在单引号字符串中的onClick参数周围转义双引号

[英]Escaping double quotes around argument of onClick in single quote string

我问的是转义这样的字符串:

function my(mstr){alert(mstr);};
document.getElementById('home').innerHTML = '<button onclick="my("a")">a</button>'

我们有
'<... onclick="fun("a")"...>'
因此其双引号位于单引号内的双引号内。

简单的'<button onclick="my(\\"a\\")">...'给出语法错误。

我知道我可以逃脱
'<button onclick="my(\\'a\\')">...'

但我想知道为什么出现此语法错误。

编辑:这是它的jsfiddle http://jsfiddle.net/pVy9W/1/

EDIT2:BallBin说它呈现<button onclick="my("a")">a</button>
试图逃避反斜杠:
'<button type="button" onclick="my(\\\\\\"a\\\\\\")">a</button>';
它呈现为奇怪:
<button type="button" onclick="my(\\" a\\")"="">a</button>
并给出错误:
Uncaught SyntaxError: Unexpected token ILLEGAL

用双引号分隔的HTML属性值中的双引号应表示为&quot; \\字符在HTML中没有特殊意义。

您的JavaScript字符串用'字符分隔,因此"不需要对JavaScript进行转义(使用\\ )。


我首先要避免将JS嵌套在JS内的HTML内。 使用DOM而不是字符串操作。

// Create button with content and an event handler
var button = document.createElement('button');
button.appendChild(document.createTextNode('a'));
button.addEventListener("click", clickHandler);

// Get container, empty it and add the button to it
var container = document.getElementById('home');
container.innerHTML = ''; // Delete all nodes inside the element
container.appendChild(button);

function clickHandler(event) {
    my("a");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM