简体   繁体   English

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

[英]Selecting element within element of same type using Jquery

I have a nested html structure like this: 我有这样的嵌套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>

And so on, it is a site map so the nesting can be as deep as you like. 依此类推,这是一个站点地图,因此嵌套可以随心所欲。

I am trying to show and hide the bar label on hover of the li element . 我试图在li element悬停时显示和隐藏bar label

With code like this: 用这样的代码:

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

The problem is, that every li parent of the current also shows its bar , how do I select it so that ONLY the current item's bar gets selected? 问题是,当前的每个li父级也会显示其bar ,如何选择它,以便仅选择当前项目的bar?

I've tried variations but just not cracked it yet. 我已经尝试过变体,但还没有破解。

Thanks. 谢谢。

Edit 1: Fixed html tags. 编辑1:固定的html标签。

You can return false from the callback function to stop further propagation of the event up the DOM tree. 您可以从回调函数返回false ,以停止事件在DOM树上的进一步传播。

And also change to using mouseover and mouseout : 并且也更改为使用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; }
});​

At this point I would like to encourage you to convert from using live to using on() , because live is deprecated. 在这一点上,我想鼓励您从使用live转换为使用on() ,因为不推荐使用live

In this case, the code becomes: 在这种情况下,代码变为:

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

Reference thanks to Yoshi : http://jsfiddle.net/6FzWU/2/ 感谢Yoshi的参考: http : //jsfiddle.net/6FzWU/2/

Use e.preventDefault() , and also .live is deprecated, use .on 使用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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM