2012-08-09 89 views
0

我有一个标准的HTML UL树:jQuery的悬停

<ul id="catTree"> 
    <li>Header 1 <span>(blah)</span> 
     <ul> 
      <li>Branch 1 <span>(blah)</span></li> 
      <li>Branch2 <span>(blah)</span></li> 

... 和一些jQuery的:

$('#catTree li').hover(
     function() { 
      $(this).children('span').css('display','inline'); 
     }, 
     function() { 
      $(this).children('span').css('display','none'); 
     } 
    ); 

默认CSS隐藏的跨度,以及jQuery的显示他们。它工作正常,除了和实际分支一样,每个父母也显示跨度。 等的悬停,它看起来像:

Header 1 (blah) 
    Branch1 (blah) 

而不是

Header1 
    Branch1 (blah) 

我知道为什么(因为这两个LIS都徘徊),但我怎么能告诉jQuery来不火上的徘徊父母?

回答

1

你可以使用:

//Note the selector. 
//Only the children li's will be selected 
$('#catTree ul > li').hover(
    function() { 
    $(this).children('span').css('display','inline'); 
    }, 
    function() { 
    $(this).children('span').css('display','none'); 
    } 
); 
+0

这仍然触发父以及 – Mark 2012-08-09 12:35:01

1

也许如果你停止传播:

$('#catTree li').hover(
     function(e) { 
      e.stopPropagation(); 
      $(this).children('span').css('display','inline'); 
     }, 
     function(e) { 
      e.stopPropagation(); 
      $(this).children('span').css('display','none'); 
     } 
    ); 

http://jsfiddle.net/techunter/B5ZwE/

但如果你先悬停在标题,然后在其子女悬停它不视为徘徊。

+0

@马克的关于内部跨度的答案是,虽然脏正确悬停。无法弄清楚如何正确地使用li将它悬停。使用跨度,我宁愿使用CSS:悬停选择器,这是更快的方式。 – TecHunter 2012-08-09 12:37:32

0

有花了年龄思考,30秒后,我的工作了发布后...

不要在LIS(因为父李覆盖儿童),悬停在一个额外的跨度,而不是徘徊:

<ul id="catTree"> 
<li><span>Header 1 <span>(blah)</span> </span> 
    <ul> 
     <li><span>Branch 1 <span>(blah)</span> </span></li> 
     <li><span>Branch2 <span>(blah)</span></span></li> 

 $(function() { 
    $('#catTree li>span').hover(
     function() { 
      $(this).children('span').css('display','inline'); 
     }, 
     function() { 
      $(this).children('span').css('display','none'); 
     } 
    ); 

});