使用Jquery在相同类型的元素中选择元素

Selecting element within element of same type using Jquery

本文关键字:元素 选择 同类型 Jquery 使用      更新时间:2023-09-26

我有一个嵌套的html结构,如下所示:

<ul class="root">
    <li>Foo 1 <label class="bar-class">bar</label>
         <ul>
            <li>Foo 2 <label class="bar-class">bar</label>
            </li>
            <li>Foo 3 <label class="bar-class">bar</label>
            </li>
        </ul>
    </li>
</ul>

等等,这是一个站点地图,所以嵌套可以随心所欲地深。

我正试图在li element悬停时显示和隐藏bar label

代码如下:

 $('.root li').live({
                mouseenter:
                       function () {
                           $(this).find('>.bar-class').show('slow');
                       },
                mouseleave:
                       function () {
                           $(this).find('>.bar-class').hide('fast');
                       }
            });

问题是,当前项的每个li父项也显示其bar,我如何选择它,以便只选择当前项的栏?

我试过变体,但还没有破解。

谢谢。

编辑1:修复html标记。

您可以从回调函数返回false,以停止事件在DOM树上的进一步传播。

也改为使用mouseovermouseout:

$('.bar-class').hide();
$('.root li').live({
  mouseover:
    function () { $(this).find('>.bar-class').show('slow'); return false; },
  mouseout:
    function () { $(this).find('>.bar-class').hide('fast'); return false; }
});​

在这一点上,我想鼓励您从使用live转换为使用on(),因为live已被弃用。

在这种情况下,代码变为:

$('.root').on('mouseover mouseout', 'li', function () {
  $(this).children('.bar-class').stop(true, true).fadeToggle('slow');
  return false;
});​

感谢Yoshi的推荐:http://jsfiddle.net/6FzWU/2/

使用e.preventDefault(),也不推荐使用.live,使用.on

$(document).on({
  mouseenter: function (e) {
    e.preventDefault();
    $(this).children('.bar-class').show('slow');
  },
  mouseleave: function (e) {
    e.preventDefault();
    $(this).children('.bar-class').hide('fast');
  }
}, '.root li');