如何在JavaScript中转义单引号(')? [英] How do I escape a single quote ( ' ) in JavaScript?

查看:183
本文介绍了如何在JavaScript中转义单引号(')?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:
我想给这个问题提供一个更新的答案。首先,让我说明你是否试图完成我在下面的内容,我建议你通过添加事件监听器。我强烈建议您为项目使用 jQuery ,并使用它们的语法管理使用DOM的事件侦听器

问题



好吧,我基本上是这样做的:

  document.getElementById(something ).innerHTML =< img src ='something'onmouseover ='change(\'ex1 \')'/>; 

我不想用双引号()放置\',我只想要一个单引号,所以我试图在它被使用时不会使它变成一个双引号,我试图在最终结果中达到这个目的。

 < img src =somethingonmouseover =change('ex1')/> 

Escaping不适用于我。



我标记的答案正常,但更清洁(更专业的方式IMO) loganfsmyth的答案

解决方案

你应该总是考虑浏览器到底会看到什么,在这种情况下,它会看到:

 < img src ='something'onmouseover ='change('ex1')'/> 

换句话说,onmouseover属性就是 change(,还有另一个叫做 ex1')'的属性没有价值。

事实是,HTML不使用 \ 作为转义字符。但它确实分别识别& quot; & $ 作为转义引号和撇号。



有了这些知识,使用这个:

  document.getElementById(something ).innerHTML =< img src ='something'onmouseover ='change(& quot; ex1& quot;)'/>; 

...也就是说,您可以使用JavaScript引号:

  document.getElementById(something)。innerHTML =< img src ='something'onmouseover ='change(\ex1\) '/>; 


UPDATE: I want to give an updated answer to this question. First, let me state if you're attempting to accomplish what I have below, I recommend that you manage events by adding event listeners instead. I highly recommend that you utilize jQuery for your project and use their syntax to manage event listeners over using DOM.

QUESTION

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.

My marked answer works fine, however, the cleaner (and more professional-looking way, IMO) is loganfsmyth's answer.

解决方案

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 &quot; and &apos; as escaped quote and apostrophe, respectively.

Armed with this knowledge, use this:

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(&quot;ex1&quot;)' />";

... That being said, you could just use JavaScript quotes:

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";

这篇关于如何在JavaScript中转义单引号(')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆