2017-04-03 58 views
0

class="up"基本上只是一个向上的箭头。查找特定类型的“最近”元素

HTML:

<div class="change_div"> <!-- change password --> 
    <div class="change_title">Change Password<i class="up"></i></div> 
    <div class="change_content" display="none"> 
    <div class="change_subtitle">Enter Password</div> 
    <input id="pw_old" class="change_input" type="password"></input> 
    <div class="change_subtitle">Enter new Password</div> 
    <input id="pw_new1" class="change_input" type="password"></input> 
    <div class="change_subtitle">Confirm new Password</div> 
    <input id="pw_new2" class="change_input" type="password"></input> 
    <div class="button_confirm" onclick="checkInput()"></div> 
    </div> 
</div> 

的jQuery:

$(document).ready(function(){ 
    $('div.change_title i').click(function() { 
    if($(this).hasClass('up')) { 
     $(this).removeClass('up'); 
     $(this).addClass('down'); 
     $('.change_content').show(); //help is needed here 
    } else if($(this).hasClass('down')) { 
     $(this).removeClass('down'); 
     $(this).addClass('up'); 
     $('.change_content').hide(); //and here 
    } 
    }) 
}); 

我有3周的div与类"change_content"并为他们3点中的箭头(1对于每个格)。 如果我点击第一个箭头,我不希望所有3个div显示/隐藏,但只有第一个。 如果我点击第二个箭头,我只想第二个div显示/隐藏。

我该如何通过使用选择器来做到这一点?

回答

1

变化

$('.change_content').show() 

$(this).parent().next('.change_content').show() 

$('.change_content').hide() 

$(this).parent().next('.change_content').hide() 
+0

'.parent元素()'太具体,我学会了用'.closest( “myBloodySelector”)'这样,我可以修改HTML和...根本不在意 –

+0

@ RokoC.Buljan在这个问题和答案中,关于'.parent()'完全没有“太具体”。 – j08691

2

您可以找到最接近的使用和明年

$(this).closest('.change_title').next('.change_content').show(); 

所以

$('div.change_title i').on('click', function() { 
    $(this).toggleClass('up down') 
      .closest('.change_title') 
      .next('.change_content') 
      .toggle() 
});