Javascript jQuery:检查下一个元素是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7678499/
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
jQuery: Checking if next element exists
提问by Lucas Veiga
Is there a way to check if an next element exists? Check my code:
有没有办法检查下一个元素是否存在?检查我的代码:
if($("#people .making-of .mask ul li.current").next("li") != null) {
alert("Exists");
}
else {
alert("Dont exists");
}
What am I doing wrong? Thanks a lot!
我究竟做错了什么?非常感谢!
回答by George
Have you tried looking at .next('li').length
?
你试过看.next('li').length
吗?
回答by Mohsen
Use jQuery .is()
, using .is()
you can even check what tag, class or ID next element have?
使用jQuery .is()
,使用.is()
您甚至可以检查下一个元素有什么标签、类或 ID?
if($("#people .making-of .mask ul li.current").next().is('li')) {
alert("Exists");
}
else {
alert("Dont exists");
}
回答by DSKrepps
The briefest method is just:
最简单的方法就是:
if( $( ... ).next('li')[0] ) {
Since jQuery functions always return a jQuery object, it's never equal to null
. But accessing a jQuery object like an array acts like you are using an array of DOM objects, so [0]
will pull the first matched DOM element or null
. Checking .length()
against 0 works, as well.
由于 jQuery 函数总是返回一个 jQuery 对象,它永远不等于null
. 但是像数组一样访问 jQuery 对象就像您在使用 DOM 对象数组一样,因此[0]
将拉取第一个匹配的 DOM 元素或null
. 检查.length()
0 也有效。
回答by Wallace Maxters
Use the length
method in jQuery:
使用length
jQuery中的方法:
if($(...).next().length > 0) {
alert("Exists.")
} else {
alert("Doesn't exist!")
}
回答by HashTagDevDude
if($("#people .making-of .mask ul li.current").next("li").length > 0) {
alert("Exists");
}
else {
alert("Dont exists");
}
回答by mattgmg1990
Like the post above says, you need to check the length of the item. Jquery.next() will always return a jquery object, but if there is no next item, it will have a length of 0.
就像上面的帖子所说,您需要检查项目的长度。jquery.next() 将始终返回一个 jquery 对象,但如果没有下一项,则它的长度为 0。
if($("#people .making-of .mask ul li.current").next("li").length > 0) {
alert("Exists");
}
else {
alert("Dont exists");
}
回答by Yogendra Tomar
I think this is good to use like.
我认为这很好用。
if ($(this).nextAll().length > 0) { alert("Exists"); }else{ alert("Don't exists"); }