Set a string of HTML equal to a variable in javascript

This question already has an answer here:

  • Creating multiline strings in JavaScript 34 answers

  • If you want to include line breaks in your actual code to make it easier to read, you're going to need to escape each one with a backslash, eg:

    var new_comment = '
        <li class="photobooth-comment">
           <span class="username">
              <a href="#">You</a>
           </span>
           <span class="comment-text">
              ' + text + '
           </span>
           <span class="comment-time">
              2d
           </span>
        </li>
    ';
    

    Or you're going to need to concatenate them as individual strings, like so:

    var new_comment = ''+
        '<li class="photobooth-comment">' +
           '<span class="username">' +
              '<a href="#">You</a>' +
           '</span>' +
           '<span class="comment-text">' +
              text +
           '</span>' +
           '<span class="comment-time">' +
              '2d' +
           '</span>' +
        '</li>'+
    '';
    

    Or simply put it all on one line:

    var new_comment = '<li class="photobooth-comment"><span class="username"><a href="#">You</a></span><span class="comment-text">' + text + '</span><span class="comment-time">2d</span></li>';
    

    Not so easy to read but neater for your JavaScript!


    The closest you can do to what you want is escaping the newline.

    new_comment = '
        <li class="photobooth-comment">
           <span class="username">
              <a href="#">You</a>
           </span>
           <span class="comment-text">
              ' + text + '
           </span>
           <span class="comment-time">
              2d
           </span>
        </li>
    ';
    

    Aside from this, you can also use string concatenation.

    (I found a possible duplicate: How to create multiline strings)


    您正在使用jquery,因此,通过jQuery,您可以将<li>放入HTML页面并使用.html()方法获取匹配元素集合中第一个元素的HTML内容,或设置每个匹配元素的HTML内容像这样的元素

     var new_comment = $(".photobooth-comment").html();
       //do what you want to 
    
    链接地址: http://www.djcxy.com/p/30436.html

    上一篇: 用javascript定义一个长字符串

    下一篇: 在javascript中设置一个等于变量的HTML字符串