我正在询问如何转义此类字符串:
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 属性值中由双引号分隔的双引号应表示为 "
\
字符在 HTML 中没有特殊意义。
您的 JavaScript 字符串由 '
字符分隔,因此 "
不需要对 JavaScript 进行转义(使用 \
)。
不过,我首先会避免将 JS 嵌套在 HTML 中的 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");
}
关于javascript - 在单引号字符串中转义 onClick 参数周围的双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24458532/