简体   繁体   中英

How can I include newlines when using appendTo(), insertAfter(), etc?

Suppose I want to add several DIVs to a container, like in this over-simplified example:

for(var x=0; x<3; x++) {
  $("<div>"+x+"</div>").appendTo("#parent");
}

The result (when viewing source) would be something like this:

<div id="parent"><div>0</div><div>1</div><div>2</div></div>

Similarly, the result of $("#parent").html() would be this:

<div>0</div><div>1</div><div>2</div>

But what if I want the source to look like this: (nevermind proper indentation)

<div id="parent">
<div>0</div>
<div>1</div>
<div>2</div>
</div>

So that the result of $("#parent").html() would instead be this:

<div>0</div>
<div>1</div>
<div>2</div>

I thought this would work, but the newline was ignored and wouldn't have accounted for the first linebreak after [div id="parent"] anyway.

for(var x=0; x<3; x++) {
  $("<div>"+x+"</div>\n").appendTo("#parent");
}

Any suggestions?

One of the reasons for the newline formatting is because the resulting HTML will need to be parsed line by line and converted to XML for storage. To complicate matters, there will be nested DIVs, like this:

<div>
  <div>0</div>
  <div>1</div>
</div>
<div>
  <div>2</div>
</div>

Without linebreaks, the above would have to be parsed as this:

<div><div>0</div><div>1</div></div><div><div>2</div></div>

If parsing the single line of HTML above is easier than inserting a bunch of newlines, then I'm all ears for the how-to and would actually prefer that!

like this? http://jsfiddle.net/swm53ran/155/

(check the console)

<div id="parent">
</div>

$(document).ready(function() {
    var html = '';
    for(var x=0; x<3; x++) {
      html += "<div>" + x + "</div>\n";
    }
    $('#parent').append(html);
    console.log($("#parent").html());
});

Using appendTo does not work, but changing the order and using append actually does work:

Try this:

$("#parent").append("<div>"+x+"</div>\n");

Instead of this:

$("<div>"+x+"</div>").appendTo("#parent");

If you are really bothered by it ...generate full strings instead which actually results in less function calls and less appends to the DOM which are expensive

var htm = '';
for(var x=0; x<3; x++) {
  htm+= "<div>" + x + "</div>\n";
}
$("#parent").append(htm);// only one append

You could even add \\t for tabbing.

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