jQuery最接近的类选择器

olo*_*olo 23 javascript jquery

<div class="wrap">
    <div class="Level2">Click me</div>
    <div class="Level3">Information</div>
</div>

<div class="wrap">
    <div class="Level2">Click me</div>
    <div class="Level3">Information</div>
</div>

<div class="wrap">
    <div class="Level2">Click me</div>
    <div class="Level3">Information</div>
</div>

<div class="wrap">
    <div class="Level2">Click me</div>
    <div class="Level3">Information</div>
</div>
Run Code Online (Sandbox Code Playgroud)

jQuery的

$('.Level2').click(function(){
   $('.Level2').closest('.Level3').fadeToggle();
});
Run Code Online (Sandbox Code Playgroud)

我想为fadeIn和fadeOut选择最接近的level3,但是不起作用.我的语法错了吗?在线样本:http://jsfiddle.net/meEUZ/

Ris*_*abh 31

尝试.next()而不是.closest()遍历DOM元素的祖先.

工作演示

你也应该使用$(this)而不是$('.Level2')选择所有.Level2而不是点击的一个.

你也可以这样做 - $(this).closest('.wrap').find('.Level3').fadeToggle();.

干杯!


rya*_*ill 15

jQuery的.closest()方法不选择兄弟选择器,而是选择父节点.看起来你正在寻找.siblings()方法.

$('.Level2').click(function(){
   $(this).siblings('.Level3').fadeToggle();
});
Run Code Online (Sandbox Code Playgroud)


Roo*_*ter 7

最近的旅行在dom树上.它找不到兄弟姐妹的东西.您可以在父级上使用查找来实现此目的

$('.Level2').click(function(){
       $(this).parent().find('.Level3').fadeToggle();
    });
Run Code Online (Sandbox Code Playgroud)


Jus*_*ill 5

是的,Jquery 中有很多方法可以找到最接近的DOM元素

$('.Level1').click(function(){
   $(this).next('.Level3').fadeToggle();
});
$('.Level2').click(function(){
   $(this).closest('.wrap').find('.Level3').fadeToggle();

});
$('.Level4').click(function(){
    $(this).parent().find('.Level3').fadeToggle(); 
});

$('.Level5').click(function(){
    $(this).siblings('.Level3').fadeToggle();
});
Run Code Online (Sandbox Code Playgroud)
.level{background:Red;width:200px;height:40px;}
.Level3{background:blue;width:300px;height:50px;}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
    <div class="Level1 level">Click me()sing next)</div>
    <div class="Level3">Information</div>
</div>

<div class="wrap">
    <div class="Level2 level">Click me(Using closest)</div>
    <div class="Level3">Information</div>
</div>

<div class="wrap">
    <div class="Level4 level">Click me(Usingh Parent)</div>
    <div class="Level3">Information</div>
</div>

<div class="wrap">
    <div class="Level5 level">Click me(Using Sibiling)</div>
    <div class="Level3">Information</div>
</div>
Run Code Online (Sandbox Code Playgroud)