jQuery jquery点击选择元素,如果它不在特定的类中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4298359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:01:16  来源:igfitidea点击:

jquery on click select element if it's not in the specific class

jqueryselectclick

提问by Dejan

I am trying to do this but no luck so far does anyone know how to select an element on click but not include elements in specific div like .boxand all content inside that div .box

我正在尝试这样做,但到目前为止还没有运气,有人知道如何在单击时选择一个元素,但不包括特定 div 中的元素,例如.box其中的所有内容div .box

small update: thank you for responses, but if i am using :notor hasClassit won't assure that elements inside that foowon't be selected. like:

小更新:感谢您的回复,但如果我正在使用:nothasClass它不能保证foo不会选择里面的元素。喜欢:

<div class=foo>this won't be selected <span>this will</span></div>

<div class=foo>this won't be selected <span>this will</span></div>

回答by Darin Dimitrov

You could use the hasClass()method:

您可以使用以下hasClass()方法:

$('a').click(function() {
    if (!(this).hasClass('foo')) {
        // the clicked element doesn't have the foo class        
    }
    return false;
});

回答by Surreal Dreams

You can also use the :not() selector.

您还可以使用 :not() 选择器。

$("#mydiv:not(.box)").click(function(){
    //do something
});

if you have specific target elements, like you want to target <li>inside your specified container, then this should be ideal:

如果你有特定的目标元素,比如你想<li>在你指定的容器内定位,那么这应该是理想的:

$("#mydiv:not(.box)>li").click(function(){
    //do something
});

This should only apply the click() function to the <li>child element of the container that's notgot the .boxclass.

这应该只适用于点击()函数将<li>是这样的容器的子元素不是得了.box类。

回答by JonMR

Assuming you're looking for anchors, this should work...

假设您正在寻找锚点,这应该有效......

$(":not(.box) a").click(function() {
  // your code here
});

However, I would suggest re-factoring your markup to make this easier. For example, you could explicitly place a clickable / notclickable class on each element.

但是,我建议重新分解您的标记以使其更容易。例如,您可以在每个元素上明确放置一个可点击/不可点击的类。