简体   繁体   English

如何遍历div并找到最近的跨度并为每个跨度添加不同的东西?

[英]How do I loop through divs and find the nearest span and add different things to each span?

For example say I had the following HTML: 例如,说我有以下HTML:

<div class="div-style">div text</div> <span>span text</span>
<div class="div-style">another div</div> <span>another span</span>
<div class="div-style">hello</div> <span>world</span>

Now what I want to do is: (using jQuery) 现在我想做的是:(使用jQuery)

  1. Go to each <div> with the class 'div-style' 使用'div-style'类转到每个<div>
  2. Find the following <span> 找到以下<span>
  3. Append the current <span> 's text to the span (in effect repeating the span text within the span text, so the first span would display 'span textspan text') 将当前<span>的文本附加到范围(实际上在范围文本中重复范围文本,因此第一个范围将显示'span textspan text')

Here you go: https://jsfiddle.net/rg9zanks/ 你去吧: https//jsfiddle.net/rg9zanks/

$('.div-style + span').each(function() {
  var span = $(this)
  span.after('<span>' + span.text() + '</span>')
})

You can take advantage of the + selector to avoid using the .next() function. 您可以利用+选择器来避免使用.next()函数。

  1. Select spans that follow elements with the class .div-style 选择具有类.div-style元素.div-style
  2. Loop through using .each() , create a new span after the selected spans using after() , and populate it with the same text using .text() . 通过循环使用.each()创建所选跨度后使用新跨越after() ,并用相同的文字填充它.text()

Literally a one-liner with jQuery, a little something like this: 字面上是一个带有jQuery的单行程序,有点像这样:

 $(".div-style + span").html(function(i,v) { return v + v; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="div-style">div text</div> <span>span text</span> <div class="div-style">another div</div> <span>another span</span> <div class="div-style">hello</div> <span>world</span> 

Further reading: 进一步阅读:

 $('.div-style').each(function(){ var t = $(this).next('span').text(); $(this).next('span').text($(this).next('span').text() + t); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="div-style">div text</div> <span>span text</span> <div class="div-style">another div</div> <span>another span</span> <div class="div-style">hello</div> <span>world</span> 

Try this 尝试这个

 $('.div-style').each(function(i, node){ var nextSpan = $(node).next(); nextSpan.append(nextSpan.html()); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="div-style">div text</div> <span>span text</span> <div class="div-style">another div</div> <span>another span</span> <div class="div-style">hello</div> <span>world</span> 

$(function () {
   $("div.div-style").next('span').each(function () {
      $(this).append($(this).text());
   });

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM