Elegant clean way to include HTML in JavaScript files?

后端 未结 7 2084
误落风尘
误落风尘 2020-12-23 10:05

I\'m building a small app with a few modal dialog windows. The windows require a tiny bit of HTML. I\'ve hard coded the window HTML in the javascript library but am not th

相关标签:
7条回答
  • 2020-12-23 10:54

    For multiline strings (no frameworks, just javascript) there are several solutions. See my answer to this SO Question. You could combine that with some simple templating:

    String.prototype.template = String.prototype.template ||
            function (){
                var  args = Array.prototype.slice.call(arguments)
                    ,str = this
                    ,i=0
                    ;
                function replacer(a){
                    var aa = parseInt(a.substr(1),10)-1;
                    return args[aa];
                }
                return  str.replace(/(\$\d+)/gm,replacer)
    };
    //basic usage:
    'some #1'.template('string'); //=> some string
    //your 'html' could look like:
    var html =
      [ '<form action="javascript:emailDone();" method="post">',
        ' <div><label for="to">To</label>',
        '       <input id="to" type="text"></div>',
        ' <div><label for="from">From</label>',
        '       <input id="from" type="text" ',
        '         value="$0"></div>',
        ' <div><label for="subject">Subject</label>',
        '      <input id="subject" type="text" disabled="disabled" ',
        '        value="$1"></div>',
        ' <div><label for="body">Body</label>',
        '      <input id="body" type="text" disabled="disabled" ',
        '        value="$2"></div>',
        ' <div><input type="submit" value="Send"><input type="button" ',
        '        value="Cancel" ',
        '        onClick="javascript:$.fancybox.close();"></div>',
        '</form>'
      ] .join('').template(email, subject, body);
    
    0 讨论(0)
提交回复
热议问题