简体   繁体   中英

How can I concatenate multiline string in javascript?

There are lots of results for the correct syntax for appending <li> 's, however I am trying to find a solution where +this['name']+ values are included in the <li> 's. firebug is displaying 'SyntaxError: unterminated string literal' and jslint is displaying 'Unclosed string' . I've tried many different variations of the placements of the commas but I haven't been able to get it to work.

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

Thank you.

you can escape end of line with backslash character \\ , like so:

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

This is due to the fact that Javascript automatically insert semi-columns sometime on line end. And in this case, you string weren't close. Another solution is to close each string on each line, and using + to concat them all.

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

(Unrelated, but you <br/> aren't allowed inside a <ul> element)

This should be much faster

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

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

You actually don't want to concatenate this at all! Consider for a moment what will happen to variable data that contains HTML or HTML-like data. Using your method, it will be parsed as such, possibly breaking things and even opening you up to XSS attack methods.

You're already using jQuery, so the proper way is easy:

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

(Note: I believe .append() allows as many parameters as you give it . If not, try using an array of elements as you append.)

you should use template literals, for more

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM