Storing HTML or XML code in javascript variables

前端 未结 4 1581
悲&欢浪女
悲&欢浪女 2021-01-21 14:16

I\'d like to store a some HTML/XML markups in a javascript variable. The problem is that the text is relatively large. For example how can I store the following XML piece in a j

相关标签:
4条回答
  • 2021-01-21 14:53

    I think you might have wanted to store html/xml code in javascript and display in textarea or some other input elements. If this is your intention this will help you.

    Instead of javascript variable, store your code in a div and hide using css ex: display:none. When you want to show the code, you can use $('#div id').text().

    0 讨论(0)
  • 2021-01-21 14:57
    var string = (<r><![CDATA[
    
       The text string goes here.  Since this is a XML CDATA section,
       stuff like <> work fine too, even if definitely invalid XML. 
    
    ]]></r>).toString();
    
    0 讨论(0)
  • 2021-01-21 15:04

    I recommend you use JSON, matey. It is less verbose. And javascript has methods to handle it nicely. In case you need to work with XML later in your classes, you can write a simple adapter.

    0 讨论(0)
  • 2021-01-21 15:06

    I assume your question is how to take that exact string, and not one you retrieve from a web service or Ajax call or the like. While this is a pretty bad idea for lots of reasons, to answer the question...


    There is no really good way of doing this in JavaScript. Some browsers support line continuation by placing a \ at the end of the line, so you would do something like:

    var xml = '<QuestionForm xmlns="[the QuestionForm schema URL]">\
      <Overview>\
        <Title>Game 01523, "X" to play</Title>\
        ...';
    

    But this is nonstandard, and in fact directly contradicts the JS spec:

    A 'LineTerminator' character cannot appear in a string literal, even if preceded by a backslash.

    The only really reliable way of doing this would be with manual string concatenation:

    var xml = '<QuestionForm xmlns="[the QuestionForm schema URL]">' + "\n" +
    '      <Overview>' + "\n" +
    '        <Title>Game 01523, "X" to play</Title>' + "\n" +
    '        ...';
    

    You can make this a bit neater like so:

    var xml = ['<QuestionForm xmlns="[the QuestionForm schema URL]">',
    '      <Overview>',
    '        <Title>Game 01523, "X" to play</Title>'
    '        ...'].join("\n");
    

    But it still sucks.

    Also, with all of these approaches, you would have to escape any single quotes, i.e. replace ' with \'. I didn't see any in your XML snippet at first glance though, which is good.

    0 讨论(0)
提交回复
热议问题