在单引号字符串中绕过onClick的参数绕过双引号 [英] Escaping double quotes around argument of onClick in single quote string
问题描述
我要求转义这样的字符串:
function my(mstr){alert(mstr);};
pre>
document.getElementById('home')。innerHTML ='< button onclick =my(a)> a< / button>'
我们有
'< ... onclick =fun(a)...>'
所以它的双引号内的单引号内的双引号。
简单
'< button onclick = 我的(\a\)> ...'
给出语法错误。
我知道我可以像
'< button onclick =my(\'a\')> ...'
但我不知道为什么会出现这种语法错误。
编辑:这里是jsfiddle的 http://jsfiddle.net/pVy9W/1/
EDIT2:BallBin表示它呈现
< button onclick =my(a)> a< / button>
so
尝试转义反斜杠:
'< button type =buttononclick =my(\\\a\\\)> a< / button>';
它呈现为奇怪:
< button type =buttononclick =my(\a\) => a< / button>
并给出错误:
未捕获的SyntaxError:意外的标记ILLEGAL
解决方案使用双引号分隔的HTML属性值内的双引号应表示为
&
\
字符在HTML中没有特殊的意义。
您的JavaScript字符串用
'
字符分隔,因此不需要转义(使用
\\ \\
)for JavaScript。
我可以避免在JS内嵌入JS内的JS第一名虽然使用DOM而不是字符串操作。
//创建具有内容和事件处理程序的按钮
var button = document。的createElement( '按钮');
button.appendChild(document.createTextNode('a'));
button.addEventListener(click,clickHandler);
//获取容器,将其清空并添加按钮
var container = document.getElementById('home');
container.innerHTML =''; //删除元素内的所有节点
container.appendChild(button);
函数clickHandler(event){
my(a);
}
I'm asking about escaping such string:
function my(mstr){alert(mstr);}; document.getElementById('home').innerHTML = '<button onclick="my("a")">a</button>'
We have
'<... onclick="fun("a")"...>'
so its double quotes inside of double quotes inside of single quotes.Simple
'<button onclick="my(\"a\")">...'
gives syntax error.
I know that i could escape it like
'<button onclick="my(\'a\')">...'
but i wonder why this syntax error appears.
EDIT: here's jsfiddle for it http://jsfiddle.net/pVy9W/1/
EDIT2: BallBin said it renders
<button onclick="my("a")">a</button>
so
trying to escape backslash:
'<button type="button" onclick="my(\\\"a\\\")">a</button>';
it renders as strange:
<button type="button" onclick="my(\" a\")"="">a</button>
and gives error:
Uncaught SyntaxError: Unexpected token ILLEGAL
解决方案Double quotes inside HTML attribute values that are delimited by double quotes should be represented as
"
The\
character has no special significance in HTML.Your JavaScript string is delimited with
'
characters so"
do not need escaping (with\
) for JavaScript.
I'd avoid nesting JS inside HTML inside JS in the first place though. Use DOM instead of string manipulation.
// 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"); }
这篇关于在单引号字符串中绕过onClick的参数绕过双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!