英文:
Array.join() functionality with JQuery elements
问题
我创建了一个元素,并向其附加了各种子元素。它们在选择器方面并不一定相似,但它们都是直接子元素。
我想在它们之间插入一个元素,用 "and" 来统一它们,但我不知道如何做。
例如;
<div id="parent">
<span>This sentence is one</span>
<span>this sentence is another</span>
</div>
应该更像是
<div id="parent">
<span>This sentence is one</span>
<span>&nbsp;and&nbsp;</span>
<span>this sentence is another</span>
</div>
它们都是顶级 div
的子元素,但有些可能是 span
,而其他可能是 a
。我不能为它们添加类或 ID。子元素的数量也是未知的,只能确定多于2个。
我的想法是获取 parent
div 的子元素,然后使用 .join("&nbsp;and&nbsp;")
,但我似乎找不到一个有条理的方法来实现。是否存在类似的逻辑?我本应该更仔细地查看文档,但今天它们似乎有些慢。
英文:
I have an element created that I append various children to. They are not all similar in any selector necessarily, but they are all direct children.
I'd like to insert an element between them to unify them with "and", but I'm spacing on how I could do that.
For instance;
<div id="parent">
<span>This sentence is one</span>
<span>this sentence is another</span>
</div>
should more resemble
<div id="parent">
<span>This sentence is one</span>
<span>&nbsp;and&nbsp;</span>
<span>this sentence is another</span>
</div>
All are children of the top level div
but some may be a span
while others an a
. I cannot add a class nor ID to them. There is also an unknown amount of children, only certain there are more than 2.
My idea was to get the children of the parent
div & then use .join("&nbsp;and&nbsp;")
but I can't seem to find a cohesive way to do so. Does similar logic exist? I'd have scrubbed docs a bit more, but they seem to be having some slowness issues today.
答案1
得分: 1
Use .after()
用于在每个子元素之后添加 span,除了最后一个。使用 .slice()
选择子元素的范围。
let children = $("#parent").children();
children.slice(0, -1).after('<span> and </span>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
<span>This sentence is one</span>
<span>this sentence is another</span>
<span>this sentence is third</span>
</div>
英文:
Use .after()
to add the span after each child except the last one. Use .slice()
to select that range of children.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let children = $("#parent").children();
children.slice(0, -1).after('<span>&nbsp;and&nbsp;</span>');
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
<span>This sentence is one</span>
<span>this sentence is another</span>
<span>this sentence is third</span>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论