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

我有一行代码:

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

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

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

有什么问题吗?

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

我试着这样写:

$('#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');




});

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

220759 次浏览

Use the not function instead:

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

hasClass only tests whether an element has a class, not will remove elements from the selected set matching the provided selector.

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.

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

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.

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

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

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.

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