使用 jQuery .append() 时在元素之间添加换行符或空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6905650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:31:59  来源:igfitidea点击:

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

jqueryappendline-breaksdom-manipulationcss

提问by Robert Koritnik

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

我有一组 jQuery 元素,可以通过调用从我的 DOM 中获取:

$(".some-selector");

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

我所有的元素都是 DIV,每个元素都在自己的行中。我的 DIV 设置了 CSS(除其他外)

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:leftthat would get rid of these spaces but that's not what I want because I would have other problems with container sizing etc.

问题是当这些 DIV 被渲染时,它们之间有空格,因为每个元素之间的文档中都有换行符。我对此很满意。我当然可以使用float:left它来摆脱这些空间,但这不是我想要的,因为我会在容器大小等方面遇到其他问题。

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:

所以。问题是我在我的 jQuery 集合中操纵这些元素的顺序,然后重新渲染它们。我主要做的是:

$(".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...

问题是它们被重新插入到 DOM 中,但没有换行符或空格......

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

将元素附加到 DOM 时,如何重新插入这些换行符?

回答by gilly3

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

重新插入元素后,使用以下命令为每个元素添加一些空格.after()

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

http://jsfiddle.net/z5cFw/

http://jsfiddle.net/z5cFw/

回答by ?ime Vidas

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

您可以map在每个 DIV 后放置一个单空格 TextNode:

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

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

现场演示:http : //jsfiddle.net/Hnv2T/

回答by Gras Double

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

?ime 的代码有一个警告:它还在最后一个元素之后添加了一个空格。

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/

现场演示:http : //jsfiddle.net/tqx19m3L/