在JavaScript变量中存储HTML或XML代码

我想在javascript变量中存储一些HTML / XML标记。 问题是文本比较大。 例如,如何将以下XML片段存储在javascript变量中?

  Game 01523, "X" to play  You are helping to decide the next move in a game of Tic-Tac-Toe. The board looks like this:    image gif  http://sofzh.miximages.com/javascript/board.gif The game board, with "X" to move.   Player "X" has the next move.    nextmove The Next Move true   What are the coordinates of the best move for player "X" in this game?        C1     likelytowin The Next Move true   How likely is it that player "X" will win this game?     radiobutton   notlikely Not likely   unsure It could go either way   likely Likely       

 var string = ( work fine too, even if definitely invalid XML. ]]>).toString(); 

我假设你的问题是如何获取那个确切的字符串,而不是从Web服务或Ajax调用中检索的字符串。 虽然出于很多原因这是一个非常糟糕的主意,但要回答这个问题……


在JavaScript中没有真正好的方法。 有些浏览器通过在行的末尾放置一个\支持行继续,所以你会做类似的事情:

 var xml = '\ \ Game 01523, "X" to play\ ...'; 

但这是非标准的,事实上直接与JS规范相矛盾:

“LineTerminator”字符不能出现在字符串文字中,即使前面有反斜杠也是如此。

唯一真正可靠的方法是使用手动字符串连接:

 var xml = '' + "\n" + ' ' + "\n" + ' Game 01523, "X" to play' + "\n" + ' ...'; 

你可以这样做一点整洁:

 var xml = ['', ' ', ' Game 01523, "X" to play' ' ...'].join("\n"); 

但它仍然很糟糕。

此外,使用所有这些方法,您必须转义任何单引号,即替换' with \' 。 我乍一看没有在你的XML片段中看到任何内容,这很好。

我想你可能想在javascript中存储html / xml代码并在textarea或其他一些输入元素中显示。 如果这是你的意图,这将对你有所帮助。

而不是javascript变量,将代码存储在div中并使用css ex: display:none隐藏。 当您想要显示代码时,可以使用$('#div id').text()

我建议你使用JSON,matey。 它不那么冗长。 并且javascript有很好的方法来处理它。 如果以后需要在类中使用XML,可以编写一个简单的适配器。