`Array.join()`功能与JQuery元素一起使用。

huangapple go评论62阅读模式
英文:

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> and </span>
  <span>this sentence is another</span>
</div>

它们都是顶级 div 的子元素,但有些可能是 span,而其他可能是 a。我不能为它们添加类或 ID。子元素的数量也是未知的,只能确定多于2个。

我的想法是获取 parent div 的子元素,然后使用 .join(" and "),但我似乎找不到一个有条理的方法来实现。是否存在类似的逻辑?我本应该更仔细地查看文档,但今天它们似乎有些慢。

英文:

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> and </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(" and ") 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>&nbsp;and&nbsp;</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 = $(&quot;#parent&quot;).children();
children.slice(0, -1).after(&#39;&lt;span&gt;&amp;nbsp;and&amp;nbsp;&lt;/span&gt;&#39;);

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;div id=&quot;parent&quot;&gt;
   &lt;span&gt;This sentence is one&lt;/span&gt;
   &lt;span&gt;this sentence is another&lt;/span&gt;
   &lt;span&gt;this sentence is third&lt;/span&gt;
&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月30日 03:46:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76584187.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定