我在 JavaScript 中是否错误地转义了字符串?
我试图在 javascript 中创建一个可点击的链接
var content = '<a href=\"#\" onclick=\"displayContent(\"TEST\")\">Whatever</a>';
$("#placeHolder").html(content);
,但我不断收到错误
未捕获的语法错误:意外的标记}
这不是转义双引号并创建链接的正确方法吗?
I am trying to create a clickable link in javascript
var content = '<a href=\"#\" onclick=\"displayContent(\"TEST\")\">Whatever</a>';
$("#placeHolder").html(content);
but I keep getting an error
Uncaught SyntaxError: Unexpected token }
Is that not the correct way to escape double quotes and create a link?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您只需要转义单引号
正如 bozdoz 所说:
但为什么不这样做
Or 正如内森所说:
You only need to escape the single quotes
As bozdoz says:
But why not do
Or as Nathan says:
您可以通过创建如下元素来避免这种混乱:
You can avoid that mess by creating elements like this:
仅当引号与开盘价和收盘价所使用的类型相同时,您才需要转义引号。在您的示例中,您不必要地转义双引号,因为您的字符串用单引号引起来。话虽这么说,由于
onclick
语句中的双引号,解析器在调用displayContent()
时会出现问题。试试这个:
You only need to escape quotes when they are the same type as used by your opening and closing quotes. In your example, you are unnecessarily escaping double quotes because your string is wrapped in single quotes. That being said, because of the double quotes in
onclick
statement the parser will have issues with the the call todisplayContent()
.Try this, instead:
你根本不需要逃避他们!
就像这样,因为通常,当嵌入
'
时,您不需要转义"
;但您确实需要转义
' 字符。
You don't need to escape them at all!
Just have it like that, as you don't need to escape
"
usually, when in embeded in a'
;But you do need to escape
'
characters when it is a parameter in a function.