How can I concatenate a multiline string in javascript?

There are many results for the correct syntax for adding <li> , however I am trying to find a solution in which the values +this['name']+ are included in the <li> . firebug displays 'SyntaxError: unterminated string literal' and jslint displays 'Unclosed string' . I tried many different options for placing commas, but I could not 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 />"); }); 

Thanks.

+4
source share
3 answers

you can escape the end of a line with a backslash character \ , for example:

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

This is because Javascript automatically inserts half-columns sometime at the end of the line. And in this case, the string was not close. Another solution is to close each line in each line and use + to concatenate them.

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

(Unbound, but you are <br/> not allowed inside the <ul> element)

+9
source

It 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/

0
source

In fact, you don’t want to concatenate this at all! Consider for a moment what happens to variable data that contains HTML or HTML-like data. Using your method, it will be analyzed as such, possibly damaging things and even revealing XSS attack methods to you.

You are already using jQuery, so the correct way is simple:

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

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

0
source

Source: https://habr.com/ru/post/1443766/


All Articles