我想在 javascript 变量中存储一些 HTML/XML 标记。问题是文字比较大。例如,如何将以下 XML 片段存储在 javascript 变量中?
<QuestionForm xmlns="[the QuestionForm schema URL]">
<Overview>
<Title>Game 01523, "X" to play</Title>
<Text>
You are helping to decide the next move in a game of Tic-Tac-Toe. The board looks like this:
</Text>
<Binary>
<MimeType>
<Type>image</Type>
<SubType>gif</SubType>
</MimeType>
<DataURL>http://tictactoe.amazon.com/game/01523/board.gif</DataURL>
<AltText>The game board, with "X" to move.</AltText>
</Binary>
<Text>
Player "X" has the next move.
</Text>
</Overview>
<Question>
<QuestionIdentifier>nextmove</QuestionIdentifier>
<DisplayName>The Next Move</DisplayName>
<IsRequired>true</IsRequired>
<QuestionContent>
<Text>
What are the coordinates of the best move for player "X" in this game?
</Text>
</QuestionContent>
<AnswerSpecification>
<FreeTextAnswer>
<Constraints>
<Length minLength="2" maxLength="2" />
</Constraints>
<DefaultText>C1</DefaultText>
</FreeTextAnswer>
</AnswerSpecification>
</Question>
<Question>
<QuestionIdentifier>likelytowin</QuestionIdentifier>
<DisplayName>The Next Move</DisplayName>
<IsRequired>true</IsRequired>
<QuestionContent>
<Text>
How likely is it that player "X" will win this game?
</Text>
</QuestionContent>
<AnswerSpecification>
<SelectionAnswer>
<StyleSuggestion>radiobutton</StyleSuggestion>
<Selections>
<Selection>
<SelectionIdentifier>notlikely</SelectionIdentifier>
<Text>Not likely</Text>
</Selection>
<Selection>
<SelectionIdentifier>unsure</SelectionIdentifier>
<Text>It could go either way</Text>
</Selection>
<Selection>
<SelectionIdentifier>likely</SelectionIdentifier>
<Text>Likely</Text>
</Selection>
</Selections>
</SelectionAnswer>
</AnswerSpecification>
</Question>
</QuestionForm>
我假设您的问题是如何获取确切的字符串,而不是从 Web 服务或 Ajax 调用等中检索的字符串。虽然出于多种原因这是一个非常糟糕的主意,但要回答这个问题......
在 JavaScript 中没有真正好的方法来做到这一点。一些浏览器通过放置一个来支持行延续\
在该行的末尾,所以你会做类似的事情:
var xml = '<QuestionForm xmlns="[the QuestionForm schema URL]">\
<Overview>\
<Title>Game 01523, "X" to play</Title>\
...';
但这是非标准的,实际上与 JS 规范直接矛盾:
“LineTerminator”字符不能
出现在字符串文字中,即使
前面有一个反斜杠。
唯一真正可靠的方法是手动字符串连接:
var xml = '<QuestionForm xmlns="[the QuestionForm schema URL]">' + "\n" +
' <Overview>' + "\n" +
' <Title>Game 01523, "X" to play</Title>' + "\n" +
' ...';
你可以让它变得更整洁,如下所示:
var xml = ['<QuestionForm xmlns="[the QuestionForm schema URL]">',
' <Overview>',
' <Title>Game 01523, "X" to play</Title>'
' ...'].join("\n");
但它仍然很糟糕。
此外,使用所有这些方法,您必须转义任何单引号,即替换'
with \'
。乍一看,我在您的 XML 片段中没有看到任何内容,这很好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)