2011-12-13 19 views
4

我所擁有的是同一類3個div,但有一個唯一的id,當我單擊一個框時,我想隱藏另一個2.如何使用jQuery定位未被點擊的同一類的項目?

這不是問題,我可以通過幾個如果/ elses或case語句可能,但我想知道是否有更通用/有效的方法來隱藏同一類的所有元素,而不是被點擊的元素?

<div id="boxes"> 
    <div id="box1" class="box">Box 1</div> 
    <div id="box2" class="box">Box 2</div> 
    <div id="box3" class="box">Box 3</div> 

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
<script type="text/javascript"> 
$(document).ready(function() { 
    $('.box').click(function() { 
     $(this).html('hi'); 
     if ($(this).attr('id') == 'box1') 
     { 
      $('#box2').hide('slow'); 
      $('#box3').hide('slow'); 
     } 
     .......... more if's  
    }); 
}); 
</script> 
+0

,如果你使用像$處理程序不要你這是點擊的元素(「盒子」)點擊(函數(element){...}? –

+0

是的,我可以得到被點擊的元素,但是一旦點擊了這個元素,我想隱藏其他2個盒子,只是尋找更有效的方法而不是使用3個條件語句。 – martincarlin87

回答

5

可以使用.not過濾功能,提及」其他「框。這樣,即使這些框不一定是DOM樹中的兄弟,或者如果有一些附加的兄弟不是框,這些代碼也可以工作。

var $boxes = $('.box'); 
$boxes.click(function() { 
    $(this).html('hi'); 
    $boxes.not(this).hide('slow'); 
}); 

請注意,我是緩存的$('.box')性能結果 - 毫無疑問這將不顯着,但沒有理由不這樣做。

4

要隱藏點擊的div的siblings

$('.box').click(function() { 
    $(this).siblings().hide("slow"); 
}); 
+0

哇,不能相信這是那麼容易,不要以爲我以前甚至聽說過兄弟姐妹。完美,謝謝! – martincarlin87

+0

@ martincarlin87 - 沒問題,任何時間:) – karim79

+0

對'.show()'的調用是不必要的。 – maxedison

0

試試這個:

$(document).ready(function() { 
    $(".box").bind("click", function(){ 
     $(".box").hide("slow"); 
     $(this).show(); 
    }); 
} 
1
$('.box').click(function() 
{ 
    var bTrigger = $(this); 
    $('.box').each(function() 
    { 
     if($(this) != bTrigger) $(this).hide('slow'); 
    }); 
}); 
1

,如果你想隱藏除點擊一個所有.box的:

$('.box').click(function() { 
    $('.box').not(this).hide('slow');  
}); 
+1

在'$(...)'中包裝'this'是不必要的。 – maxedison

+0

啊ic ..感謝maxedison – bondythegreat

相關問題