Javascript 如何在 jQuery 中使用 :not 和 hasClass() 来获取没有类的特定元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8743026/
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-24 07:18:10  来源:igfitidea点击:

How to use in jQuery :not and hasClass() to get a specific element without a class

javascriptjqueryhtmlaccordion

提问by Alon

I have this line of code:

我有这行代码:

$('#sitesAccordion .groupOfSites').click(function() {
    var lastOpenSite = $(this).siblings().hasClass(':not(.closedTab)');
    console.log(lastOpenSite);
});

I get "false" instead of getting one of the other elements (assuming that there is one - and there must be). I guess the problem is with:

我得到“假”而不是得到其他元素之一(假设有一个 - 必须有)。我想问题在于:

.hasClass(':not(.closedTab)');

What is the problem?

问题是什么?

My purpose is to create my own accordion (without using jQuery UI)

我的目的是创建我自己的手风琴(不使用 jQuery UI)

and I am trying to write it like this:

我正在尝试这样写:

$('#sitesAccordion .groupOfSites').click(function() {

    //Get the last opened tab
    var lastOpenSite = $(this).siblings().hasClass(':not(.closedTab)');

    //Close last opened tab and add class
    lastOpenSite.hide().toggleClass('closedTab');

    //Open the current Tab
    $(this).children('.accordionContent').toggle('fast');

    // remove class from open tab
    $(this).toggleClass('closedTab');


});

Is this the best way? thanks, Alon

这是最好的方法吗?谢谢,阿隆

回答by Dennis

Use the notfunction instead:

改用该not函数:

var lastOpenSite = $(this).siblings().not('.closedTab');

hasClassonly tests whether an element has a class, notwill remove elements from the selected set matching the provided selector.

hasClass仅测试元素是否具有类,not将从与提供的选择器匹配的选定集合中删除元素。

回答by Qar

It's much easier to do like this:

这样做要容易得多:

if(!$('#foo').hasClass('bar')) { 
  ...
}

The ! in front of the criteria means false, works in most programming languages.

这 !前面的标准意味着 false,适用于大多数编程语言。

回答by techfoobar

jQuery's hasClass()method returns a boolean (true/false) and not an element. Also, the parameter to be given to it is a class name and not a selector as such.

jQuery 的hasClass()方法返回一个布尔值(真/假)而不是一个元素。此外,要给它的参数是一个类名,而不是一个选择器。

For ex: x.hasClass('error');

例如: x.hasClass('error');

回答by Sampat Badhe

You can also use jQuery - is(selector) Method:

您还可以使用jQuery - is(selector) 方法

var lastOpenSite = $(this).siblings().is(':not(.closedTab)');

回答by devRyan

I don't know if this was true at the time of the original posting, but the siblings method allows selectors, so a reduction of what the OP listed should work.

我不知道在原始发布时这是否属实,但是兄弟姐妹方法允许选择器,因此减少列出的 OP 应该起作用。

 $(this).siblings(':not(.closedTab)');