问题描述
好吧,我基本上这样做
document.getElementById(something)。innerHTML =< img src ='something'onmouseover ='change(\'ex1\')'/>;
我不想要双引号(),我把\'我只想要一个单引号,所以我试图不把它放在一个双重的时候,我使用最终结果。
< img src =somethingonmouseover =change('ex1')/>
Escaping不适用于我。
更新:我标记的答案工作正常,但是,更清洁专业的方式,IMO)是这个答案:
你应该总是考虑浏览器到底会看到什么,在这种情况下,它会看到这样:
< img src ='something'onmouseover ='change('ex1')'/>
换句话说,onmouseover属性只是更改(
,而t这是另一个名为 ex1')'
的属性,没有价值。
事实是,HTML不使用 \
为转义字符。但是它确实分别将& quot;
和&'/ code>识别为转义的引号和撇号。 >
使用这个知识:
document.getElementById(something ).innerHTML =< img src ='something'onmouseover ='change(& quot; ex1& quot))'/>;
...这就是说,你可以使用JavaScript引号:
document.getElementById(something)。innerHTML =< img src ='something'onmouseover ='change(\ex1\) '/>;
Okay, I am basically doing this
document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\'ex1\')' />";
I don't want double quotes (") where I put the \'. I only want a single quote, so I am trying to not make it put a double when it is used. I am trying to reach this in the final outcome.
<img src="something" onmouseover="change('ex1')" />
Escaping isn't working for me.
UPDATE: My marked answer works fine, however, the cleaner (and more professional-looking way, IMO) is this answer: https://stackoverflow.com/a/16134953/1754890
解决方案
You should always consider what the browser will see by the end. In this case, it will see this:
<img src='something' onmouseover='change(' ex1')' />
In other words, the "onmouseover" attribute is just
change(
, and there's another "attribute" called ex1')'
with no value.
The truth is, HTML does not use
\
for an escape character. But it does recognise "
and '
as escaped quote and apostrophe, respectively.
Armed with this knowledge, use this:
document.getElementById("something").innerHTML = "<img src='something' onmouseover='change("ex1")' />";
... That being said, you could just use JavaScript quotes:
document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";
这篇关于如何在JavaScript中避免单引号(')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!