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
How to use in jQuery :not and hasClass() to get a specific element without a class
提问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
回答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)');