2010-11-01 66 views
0

如何選擇某個<div>以外的所有子元素,但活動的元素除外?例如:jquery選擇器問題

<div> 
    <a id="1" class="item" href="#">Item 1 </a> 
    <a id="2" class="item" href="#">Item 2 </a> 
    <a id="3" class="item" href="#">Item 3 </a> 
</div> 

<script> 
$(function() { 
    $(".item").mouseover(function() { 


     // HOW TO hide all the items with class item except this one 


    }); 
}); 

回答

1

您可以使用.not()排除this(當前元素),就像這樣:

$(function() { 
    $(".item").mouseover(function() { 
     $(".item").not(this).hide(); 
    }); 
}); 

或者,如果他們總是兄弟姐妹使用.siblings(),就像這樣:

$(function() { 
    $(".item").mouseover(function() { 
     $(".item").siblings().hide(); 
    }); 
}); 
+0

好主人,我打敗@Nick Craver(幾乎相同的答案)整整17秒* O_O雖然,雖然,我的變化沒有奏效,所以這確實需要一些快樂...... =/ – 2010-11-01 13:41:39

+0

@David - 你的回答會拋出一些非常奇怪的錯誤,'this'不是一個字符串,它是一個DOM元素。 – 2010-11-01 13:42:23

+0

確實,請參閱上面的我的(編輯)評論。詛咒 – 2010-11-01 13:44:35

1
$('.item').not($(this).show()).hide(); 
+0

哈哈我做了同樣的答案=) 刪除它雖然 – Breezer 2010-11-01 13:43:10

+0

沒有必要包裝'this'或'.show()'它...如果它不*已經*可見,我們不能把它挖出來。 – 2010-11-01 13:45:20

0

不同的想法...隱藏所有,然後告訴我:

$(function() { 
    $(".item").mouseover(function() { 

     // Hide all: 
     $('.item').hide(); 

     // Show "me": 
     $(this).show(); 


    }); 
}); 
0

可以使用$(this)選擇過度除了在鼠標的項目。