Add line breaks or spaces between elements when using jQuery .append()

非 Y 不嫁゛ 提交于 2021-02-18 19:52:40

问题


I have a jQuery set of elements that I get from my DOM by calling:

$(".some-selector");

All my elements are DIVs each in its own line. My DIVs are set CSS (among other things)

display: inline-block;

which prevents them from rendering as block elements (each in its own line).

The problem is that when these DIV are rendered they have spaces between them because there's line break in the document between each element. I'm comfortable with that. I could of course use float:left that would get rid of these spaces but that's not what I want because I would have other problems with container sizing etc.

So. The problem is that I manipulate the order of these elements in my jQuery set an then rerender them. What I essentially do is:

$(".some-selector").detach().manipulate().appendTo(".container");
// or equivalent
$(".container").append($(".some-selector").detach().manipulate());

The problem is that they get re-inserted into the DOM, but without line breaks or spaces...

How do I get these line breaks back in when appending my elements into DOM?


回答1:


After you re-insert your elements, append some whitespace to each of them using .after():

$(".some-selector").after(" ");

http://jsfiddle.net/z5cFw/




回答2:


You could use map to put a single-space TextNode after each DIV:

$('.some-selector').detach().manipulate().map(function() {
    return [this, document.createTextNode(' ')];
}).appendTo('.container');

Live demo: http://jsfiddle.net/Hnv2T/




回答3:


Šime's code has a caveat: it also adds a space after the last element.

Here is a version that avoids that space:

$('.some-selector').detach().manipulate().map(function (index, element) {
    return index === 0 ? element : [document.createTextNode(' '), element];
}).appendTo('.container');

Live demo: http://jsfiddle.net/tqx19m3L/



来源:https://stackoverflow.com/questions/6905650/add-line-breaks-or-spaces-between-elements-when-using-jquery-append

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!