a more graceful multi-line javascript string method

后端 未结 5 471
轻奢々
轻奢々 2021-01-12 04:22

The only way I know how to print a huge string without using += is to use \\ backslashes. ugly!

5条回答
  •  悲哀的现实
    2021-01-12 04:45

    In general, the answer is: not in the language syntax. Though as Ken pointed out in his answer there are many work-arounds (my personal method is to load a file via AJAX). In your specific case though, I'd prefer creating a HTML constructor function so you can then define the HTML structure using javascript object literals. Something like:

    var longString = makeHTML([{
      div : {
        id : "lol",
        children : [{
          div : {
            id : "otherstuff",
            children : [{
                text : "test content. maybe some code"
            }]
        }]
     }]
    

    which I find to be much easier to handle. Plus, you this would allow you to use real function literals when you need it to avoid string quoting hell:

    makeHTML([{
      span : {
        onclick : function (event) {/* do something */}
      }
    }]);
    

    note: the implementation of makeHTML is left as exercise for the reader


    Additional answer:

    Found some old code after a quick scan through my hard disk. It's a bit different from what I suggested above so I thought I'd share it to illustrate one of the many ways you can write functions like this. Javascript is a very flexible language and there is not much that forces you to write code one way or another. Choose the API you feel most natural and comfortable and write code to implement it.

    Here's the code:

    function makeElement (tag, spec, children) {
        var el = document.createElement(tag);
        for (var n in spec) {
            if (n == 'style') {
                setStyle(el,spec[n]);
            }
            else {
                el[n] = spec[n];
            }
        }
        if (children && children.length) {
            for (var i=0; i

    Using it would be something like:

    document.getElementById('foo').appendChild(
      makeElement(div,{id:"lol"},[
        makeElement(div,{id:"otherstuff"},[
          makeText("test content. maybe some code")
        ])
      ])
    );
    
    /* implementation of makeText is
     * left as exercise for the reader
     */
    

提交回复
热议问题