HTML:在引号内使用引号内的引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19845167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML:Use quotes within quotes within quotes
提问by flimmerkiste
I'm stuck with this problem:
我被这个问题困住了:
<body onload="document.body.innerHTML="<script>alert('hi')</script>"">
The problem is that i cant use quotes within quotes within quotes. Any ideas?
问题是我不能在引号内的引号内使用引号。有任何想法吗?
回答by Quentin
To represent a "
character inside an HTML attribute delimited by "
characters, use the entity "
要表示"
由"
字符分隔的 HTML 属性内的字符,请使用实体"
I'd recommend attaching event listeners using JavaScriptrather then using intrinsic event attributes though. It simplifies things greatly.
我建议使用 JavaScript 附加事件侦听器,而不是使用内部事件属性。它大大简化了事情。
Note however, that browsers will not execute JavaScript added to the document with innerHTML
. If you want to add a script programatically, the use createElement
/ appendChild
et al.
但是请注意,浏览器不会执行添加到带有innerHTML
. 如果要以编程方式添加脚本,请使用createElement
/ appendChild
et al.
回答by Mageek
<body onload='document.body.innerHTML="<script>alert(\"hi\")</script>"'>
or
或者
<body onload="document.body.innerHTML='<script>alert(\'hi\')</script>'">
It does work, but the script doesn't get executed because it is added after the browser parsed your code.
它确实有效,但脚本不会被执行,因为它是在浏览器解析您的代码后添加的。
Note that if you wanted quotes within quotes within quotes within quotes you would have done: <body onload="document.body.innerHTML='<script>alert(\'\\\'hi\\\'\')</script>'" >
请注意,如果您想要引号内的引号内的引号内的引号,您会这样做: <body onload="document.body.innerHTML='<script>alert(\'\\\'hi\\\'\')</script>'" >
What is really impossible (i think) without "
is putting "
and '
in the alert.
没有真正不可能的(我认为)"
是投入"
并'
保持警惕。
回答by talemyn
Gah! First off, don't do it that way. :D
嘎!首先,不要那样做。:D
Something like:
就像是:
<body></body>
<script>
window.onload = function () {
document.body.innerHTML = "<script>alert('hi')</script>";
}
</script>
. . . would be better. Consider some JQuery solutions, as well.
. . . 会更好。也考虑一些 JQuery 解决方案。
Even that specific approach, I wouldn't recommend, but I suspect that you are simply testing out how to add content to the body of your HTML after the page is loaded, rather than actually wanting to use the alert()
. ;) If that's the case, try something like this:
即使是那种特定的方法,我也不推荐,但我怀疑您只是在测试如何在页面加载后向 HTML 正文添加内容,而不是实际想要使用alert()
. ;) 如果是这种情况,请尝试以下操作:
<body></body>
<script>
window.onload = function () {
document.body.innerHTML = "some text";
alert('hi'); // if you really want to test that the JS is working after load.
}
</script>