对象文字语法错误中的JavaScript字符串文字

时间:2013-06-22 11:43:32

标签: javascript

我试图将一些html标记放在数组中以便稍后检索。我的编辑器在description1行上抛出语法错误,我无法弄清楚原因。任何帮助将非常感激。代码如下。谢谢A

var modalcontent = {
  description1 : '<div id = "description"><div class = "tbc">  
  <label class = "tbc" for = "tbc">Description</label>
  </div>
  <div class = "tbc">
  <input type = "text" class = "tbc" name = "description" id = "tbc" placeholder =        "Enter description">
  </div>
</div>
<!--end description div-->'
} 

1 个答案:

答案 0 :(得分:6)

你有一个未闭合的字符串文字。默认情况下,JavaScript字符串多行。

var modalcontent = {
  description1 : '<div id = "description"><div class = "tbc"> '+
  '<label class = "tbc" for = "tbc">Description</label>'+
  '</div>'+
  '<div class = "tbc">'+
  '<input type = "text" class = "tbc" name = "description" id = "tbc" placeholder = "Enter description">'+
  '</div>'+
  '</div>'+
  '<!--end description div-->'
} 

(fiddle)

或者,您可以使用\字符创建多行字符串,这些字符仅适用于较新的实现。请参阅this related questionthe language specification

注意:将HTML存储在字符串中通常不是最佳选择,这使得调试和使用更加困难。您通常可以使用模板。并不是没有好用例,只是很少见。