簡體   English   中英

如何在JavaScript中連接多行字符串?

[英]How can I concatenate multiline string in javascript?

對於添加<li>的正確語法,有很多結果,但是我正在嘗試找到一種解決方案,其中+this['name']+值包含在<li> firebug顯示'SyntaxError: unterminated string literal'而jslint顯示'Unclosed string' 我已經嘗試了逗號位置的許多不同變體,但無法使其正常工作。

 $.each(data.result, function() {
     $("ul").append("<li>Name: "+this['name']+"</li>
                     <li>Age: "+this['age']+"</li>
                     <li>Company: "+this['company']+"</li>
                     <br />");
 });

謝謝。

您可以使用反斜杠字符\\來換行,如下所示:

 $.each(data.result, function(){
 $("ul").append("<li>Name: " + this['name'] + "</li> \
     <li>Age: " + this['age'] + "</li> \
     <li>Company: "+this['company']+"</li> \
     <br />");
 });

這是因為Javascript會在行尾的某個時間自動插入半列。 在這種情況下,您的字符串不是緊密的。 另一種解決方案是關閉每行上的每個字符串,並使用+合並它們。

 $.each(data.result, function(){
 $("ul").append("<li>Name: " + this['name'] + "</li>" +
     "<li>Age: " + this['age'] + "</li>" +
     "<li>Company: "+this['company']+"</li>" +
     "<br />");
 });

(無關,但<ul>元素內不允許您使用<br/>

這應該更快

 li = '';
 $.each(data.result, function(){
     li += "<li>Name: " + this['name'] + "</li>" +
          "<li>Age: " + this['age'] + "</li>" +
          "<li>Company: "+this['company']+"</li>" +
          "<br />"; // could remove this and use css
 });

 $("ul").append(li);

參見http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/

您實際上根本不想將其串聯起來! 考慮一下包含HTML或類似HTML的數據的可變數據會發生什么。 使用您的方法,它將被如此解析,可能會破壞事物,甚至使您對XSS攻擊方法開放。

您已經在使用jQuery,因此正確的方法很簡單:

$('ul').append(
    $('<li/>').text('Name: ' + this.name), 
    $('<li/>').text('Age: ' + this.age),
    // etc.
);

(注意:我相信.append() 允許您提供盡可能多的參數 。如果不允許,請嘗試在添加時使用元素數組。)

您應該使用模板文字,以獲取更多信息

$.each(data.result, function() {
     $("ul").append(`<li>Name: ${this['name']} </li>
       <li>Age: ${this['age']} </li>
       <li>Company: ${this['company']} </li>
       <br />
     `);
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM