<< END喜欢javascript中的构造

sti*_*mms 0 javascript

我有一大块HTML,它是使用AJAX添加的一些数据的模板.我想将块存储在一个变量中,然后对其中的标记进行替换,但我不想弄乱html的格式以将其转换为javascript字符串.有没有像这样的东西

<<END 
Run Code Online (Sandbox Code Playgroud)

perl中的命令会读取字符串中的所有内容,直到它到达结束标记为止?

Jam*_*mes 6

不,遗憾的是,JavaScript中没有这样的构造.

你有几个不同的选择,每个选项都有自己的优点:

  1. 字符串连接

    :

    var html = '<div id="something">' +
                   '<p>Lots of HTML</p>' +
                   '<p>Lots of HTML</p>' +
                   '<p>Lots of HTML</p>' +
               '</div>';
    
    Run Code Online (Sandbox Code Playgroud)
  2. 逃离 newline

    :

    var html = '<div id="something">\
                   <p>Lots of HTML</p>\
                   <p>Lots of HTML</p>\
                   <p>Lots of HTML</p>\
                </div>';
    
    Run Code Online (Sandbox Code Playgroud)
  3. 阵列加入

    :

    var html = [
        '<div id="something">',
            '<p>Lots of HTML</p>',
            '<p>Lots of HTML</p>',
            '<p>Lots of HTML</p>',
        '</div>'
    ].join('');
    
    Run Code Online (Sandbox Code Playgroud)
  4. 将其存储在任意隐藏元素中

    :

    HTML:

    <textarea id="template" style="display:none;">
        <div id="something">
            <p>Lots of HTML</p>
            <p>Lots of HTML</p>
            <p>Lots of HTML</p>
        </div>
    </textarea>
    
    Run Code Online (Sandbox Code Playgroud)

    JavaScript的:

    var html = document.getElementById('template').value;
    
    Run Code Online (Sandbox Code Playgroud)

    我更喜欢使用<script type="text/html">s或HTML注释,但<textarea>似乎很受欢迎.

  5. 使用完整的模板引擎,如

    :