jQuery-“不包含元素"的规则; [英] jQuery - rule for "does not contain element"

查看:55
本文介绍了jQuery-“不包含元素"的规则;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在下面创建一个定位a元素的规则:

I want to create a rule to target the a element in the following:

<ul id="root">
   <li>
      <a href="item.html">Root Menu Item</a>
   </li>
</ul>

但是,如果li元素包含另一个ul元素,例如:

However this should not apply if the li element contains another ul element, e.g:

<ul id="root">
   <li>
      <a href="#">Sub Menu</a>
      <ul>
         <li>
            <a href="item.html">Sub Menu Item</a>
        </li>
      </ul>
   </li>
</ul>

我已根据需要创建了该事件,但需要该事件仅在根"菜单项上起作用.

I have created the event as required but need it to only work on the "root" menu items.

我知道我只能添加一个id属性来仅定位所需的元素,但是我的客户端安装的菜单插件不容易配置.

I know I can just add an id attribute to target the desired element only but the menu plugin that my client has installed is not easily configurable.

推荐答案

如果您匹配a,请执行以下操作:

If you're matching the a do this:

var result  = $('#root > li:not(:has(ul)) > a');

  • http://api.jquery.com/not-selector/
  • http://api.jquery.com/has-selector/
    • http://api.jquery.com/not-selector/
    • http://api.jquery.com/has-selector/
    • 如果您想允许嵌套更深的<ul>元素,并且只想检查以确保只有直接子元素没有<ul>,则可以执行以下操作:

      If you want to allow deeper nested <ul> elements, and just want to check to make sure only the direct children don't have a <ul>, you could do this:

      var result  = $('#root > li:not(:has(> ul)) > a');
      


      要同时具有多个选择器,请在引号内用逗号分隔它们:

      To have more than one selector at the same time, separate them with a comma inside the quotes:

      var result  = $('#root > li:not(:has(> ul)) > a, #someOtherElement');
      

      这篇关于jQuery-“不包含元素"的规则;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆