简体   繁体   English

jQuery在下一个元素内选择一个嵌套元素

[英]Jquery selecting a nested element inside the next element

from the structure below I am trying to place a class on the span that follows the button but I cant seem to traverse into the div containing the span. 从下面的结构中,我试图在按钮后面的跨度上放置一个类,但是我似乎无法遍历包含跨度的div。

I can target the div fine using: 我可以使用以下方法定位div:

$("button").next('div').addClass('alert');

But can't get that class applied to the span directly using: 但是不能使用以下方法将该类直接应用于范围:

$("button").next('div > span').addClass('alert');

or 要么

$("button").next('div').next('span').addClass('alert');

My example structure is 我的示例结构是

<button>Click</button>
  <div>
    <span></span>
  </div>
<button>Click</button>
  <div>
    <span></span>
  </div>

You need to use find function. 您需要使用查找功能。

Please try this: 请尝试以下方法:

$("button").next('div').find('span').addClass('alert');

 $("button").next('div').find('span').addClass('alert'); 
 .alert{ color:red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>Click</button> <div> <span>abc</span> </div> <button>Click</button> <div> <span>def</span> </div> 

Another solution is to use children method. 另一个解决方案是使用方法。

 $("button").next('div').children('span').addClass('alert'); 
 .alert{ color:red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>Click</button> <div> <span>abc</span> </div> <button>Click</button> <div> <span>def</span> </div> 

 $("button").next('div').find('span').addClass('alert'); 
 .alert{color:red} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>Click</button> <div> <span>this</span> </div> <button>Click</button> <div> <span>this</span> </div> 

This should work. 这应该工作。 use .next() with .find() .find()一起使用.next() .find()

You can do like this 你可以这样

$("button").on('click',function(){
 $(this).next('div').find('span').addClass('alert');
})

DEMO 演示

If you need to add class to span where button is clicked you need to handle click event of button 如果您需要添加类来span单击button则需要处理button click event

$(function () {
  $("button").click(function () {
     $(this).next('div').find('span').addClass('alert');
   });
});

As per the documentation, next() traverses siblings: 根据文档,next()遍历兄弟姐妹:

.next( [selector ] )
Description: Get the immediately following sibling of each element in the set 
of matched elements. If a selector is provided, it retrieves the next sibling 
only if it matches that selector.

So you need to be using children() instead. 因此,您需要改为使用children()。

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

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