简体   繁体   English

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

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

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 谢谢,Alon

Use the not function instead: 请改用not函数:

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. hasClass仅测试元素是否具有类, not从与所提供的选择器匹配的所选集合中删除元素。

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. 在标准前面表示错误,适用于大多数编程语言。

jQuery's hasClass() method returns a boolean (true/false) and not an element. jQuery的hasClass()方法返回一个布尔值(true / false)而不是一个元素。 Also, the parameter to be given to it is a class name and not a selector as such. 此外,要赋予它的参数是类名而不是选择器。

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

你也可以使用jQuery - is(selector)方法

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM