2013-04-28 163 views
1

HTML:顯示隱藏的div

我有每個L1的UL列表counstructed這樣的:

<li class="A">list-item 
    <div>1</div> 
    <div class="B">2 
     <div class="C">3</div> 
    </div> 

    </li> 

其中DIV C有CSS屬性顯示:無; 我寫了這個JS:

$(".A").hover(function() { 
    $(".C").toggle(); 
    }); 

,顯示李懸停隱藏層,但我想JS只在活躍的李項工作。 因此,當我懸停李項目它只顯示該列表項隱藏div。

有什麼建議嗎?我是新的js,所以任何幫助將不勝感激thnx!

回答

2

使用context可將查找縮小到所需元素的子元素。

$(".A").hover(function() { 
    $(".C", this).toggle(); 
}); 
+0

+1只是因爲你不使用find和BTW,因爲它的工作 – 2013-04-28 14:17:42

+0

@smerny它是一個非常neglig ible的區別,否則這種方法不會由'jQuery'提供。 – 2013-04-28 14:22:15

+1

這種差異可以忽略的原因是因爲jQuery在內部使用'find()'方法來應用選擇器上下文。 – 2013-04-28 14:25:08

3

嘗試這樣的事情,它會發現內thisC(這將是該元件徘徊)

$(".A").hover(function() { 
    $(this).find(".C").toggle(); 
}); 
2

使用hover()hover功能的正確格式爲:

$(".A").hover(
    function() { 
    // A function to execute when the mouse pointer enters the element. 
    $(this).find(".C").show(); 
    }, 
    function() { 
    // A function to execute when the mouse pointer leaves the element. 
    $(this).find(".C").hide(); 
    } 
); 
+0

因爲.C本來是隱藏的,只用toggle就會有同樣的影響:http://jsfiddle.net/M3TE9/ – smerny 2013-04-28 14:29:18