简体   繁体   English

javascript的引号问题

[英]javascript's quotation mark question

I have a very simple question. 我有一个非常简单的问题。

I have the following code 我有以下代码

var replyName = "1";

var test = "<div id=replyName></div>"

I want to set the class name to replyName, what should I do? 我想将类名设置为replyName,该怎么办?

Thank you very much 非常感谢你

You really have three options. 您确实有三个选择。

  1. Use the opposite quote style, in this case single quotes, to surround the attribute declaration. 使用相反的引号样式(在这种情况下为单引号)包围属性声明。

     var test = "<div id='"+replyName+"' class='"+replyName+"'></div>"; 
  2. Use escaped quotes. 使用转义引号。

     var test = "<div id=\\""+replyName+"\\" class=\\""+replyName+"\\"></div>"; 
  3. Use no quotes (beware this can cause problems if you have spaces, for instance, although an ID should not have spaces anyways). 不要使用引号(例如,请注意,如果您有空格,这可能会引起问题,尽管ID始终不应该有空格)。 However, multiple classes would have spaces, so be careful, since in the below case those spaces would be interpreted as different attributes. 但是,多个类将具有空格,因此请小心,因为在以下情况下,这些空格将被解释​​为不同的属性。

     var test = "<div id="+replyName+" class="+replyName+"></div>" 

I would use 1 or 2, although 3 is valid under the right conditions. 我将使用1或2,尽管3在正确的条件下有效。

Also, as Mikola mentions in a comment below, if you flip the string quote style to single quotes, you'll have to use the opposite quoted style for your attribute a la 1, and escape single quotes like I do double quotes in 2. 同样,正如Mikola在下面的评论中提到的那样,如果将字符串引用样式翻转为单引号,则必须为属性使用相反的引号样式la 1,并像在2中对双引号一样进行转义。

http://jsfiddle.net/XyVuN/1/ http://jsfiddle.net/XyVuN/1/

var replyName = "1";
var test = "<div id='" + replyName + "'></div>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM