对于href使用JavaScript单引号和双引号 [英] Using JavaScript single and double quotes for href's
问题描述
我有问题可以在 href
的JavaScript函数中转义单引号和双引号。
I am having problem with escaping the single and double quotes inside the href
s JavaScript function.
我有 href
中的JavaScript代码。这就像 -
I have this JavaScript code inside href
. It's like -
<a href = "javascript:myFunc("fileDir/fileName.doc", true)"> click this </a>
现在,由于双引号内的双引号无效,我需要将内部双引号它被视为字符串的一部分 -
所以,我需要这样做 -
Now, since double quotes inside double quote is not valid, I need to escape the inner double quotes for it to be treated as part of the string - so, I need to do this -
<a href = "javascript:myFunc(\"fileDir/fileName.doc\" , true)"> click this </a>
问题是,即使上述代码不起作用。 JavaScript代码被截断 - myFunc(
The problem is, even the above code is not working. The JavaScript code is getting truncated at -- myFunc(
我尝试过单引号变体,这似乎不起作用(这意味着如果我的字符串中的单引号字面值代码被截断)。
I tried with the single quote variation too - but even that doesn't seem to work (meaning that if I have a single quote inside my string literal then the code gets truncated).
这是我用一个单一的引用:
This is what I did with a single quote:
<a href = 'javascript:myFunc("fileDir/fileName.doc" , true)'> click this </a>
这有效,但是如果我在字符串中有一个单引号,那么代码被截取与双引号一样。
This works, but if I have a single quote inside the string then the code gets truncated in the same way as that of double quotes one.
推荐答案
使用反斜杠来转义引号是如何在JavaScript中工作的,但是您实际上并没有在其中编写JavaScript代码:您正在编写HTML,您可以使用HTML转义方法:字符实体。
Using backslashes to escape quotes is how it works in JavaScript, but you're not actually writing JavaScript code there: you're writing HTML. You can do it by using the HTML escaping method: character entities.
" // "
' // '
例如:
<a href="javascript: alert('John O'Brien says "Hi!"');">...</a>
这篇关于对于href使用JavaScript单引号和双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!