[英]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屬性值中的雙引號應表示為"
\\
字符在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.