将一个HTML字符串设置为等于javascript中的一个变量

Set a string of HTML equal to a variable in javascript

本文关键字:一个 javascript 变量 字符串 HTML 设置      更新时间:2023-09-26

我声明一个HTML字符串,并将其设置为等于一个变量。我想不出它会产生错误的任何原因,但它是:

未捕获的语法错误:Ln 136上出现意外的标识符。

Ln 136: 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>
';

如果你想在实际代码中包含换行符以便于阅读,你需要用反斜杠来转义每个换行符,例如:

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>'
';

或者你需要将它们连接为单独的字符串,比如:

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>'+
'';

或者简单地将其全部放在一行:

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>';

不那么容易阅读,但更整洁的JavaScript!

您能做的最接近您想要做的事情就是转义换行符。

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>'
';

除此之外,您还可以使用字符串串联。

(我发现了一个可能的重复:如何创建多行字符串)

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

 var new_comment = $(".photobooth-comment").html();
   //do what you want to 

这里有一个顽皮的PHP启发方法。我把它贴在这里作为一种心理锻炼。请不要投反对票。。。

演示

var new_comment; /*<<<EOF 
    <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>
EOF*/
// note the script tag here is the hardcoded as the first tag 
new_comment=document.getElementsByTagName('script')[0].innerHTML.split("EOF")[1]; 
alert(new_comment.replace('$text','Here goes some text'));