在单引号字符串中转换onClick参数的双引号

时间:2014-06-27 18:21:38

标签: javascript escaping

我要求逃避这样的字符串:

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 for 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

1 个答案:

答案 0 :(得分:1)

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

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


我首先避免在JS内部将JS嵌套在JS中。使用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");
}
相关问题