2017-04-03 33 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() 
});