2013-04-28 160 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