jQuery——“不包含元素”的规则

时间:2021-12-23 16:55:38

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

我想创建一个规则来针对以下a元素:

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

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

但是,如果li元素包含另一个ul元素,则不应采用这种方法,例如:

<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.

我按要求创建了事件,但只需要在“根”菜单项上工作。

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.

我知道我可以只添加一个id属性来针对所需的元素,但是我的客户端安装的菜单插件是不容易配置的。

2 个解决方案

#1


40  

If you're matching the a do this:

如果你要匹配a,请这样做:

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

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');

EDIT:

编辑:

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');

#2


2  

$('#root a').click(function(e) {
    if ( $(this).parents('ul').length > 1 ) {
       e.preventDefault(); // cancel action for anchors inside of #root who have multiple parent list elements 
    }
});

Change logic per requirement.

改变逻辑/要求。

#1


40  

If you're matching the a do this:

如果你要匹配a,请这样做:

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

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');

EDIT:

编辑:

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');

#2


2  

$('#root a').click(function(e) {
    if ( $(this).parents('ul').length > 1 ) {
       e.preventDefault(); // cancel action for anchors inside of #root who have multiple parent list elements 
    }
});

Change logic per requirement.

改变逻辑/要求。