Luc*_*iga 52 javascript jquery
有没有办法检查下一个元素是否存在?检查我的代码:
if($("#people .making-of .mask ul li.current").next("li") != null) {
alert("Exists");
}
else {
alert("Dont exists");
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?非常感谢!
Moh*_*sen 24
使用jQuery .is(),使用.is()你甚至可以检查下一个元素有哪些标签,类或ID?
if($("#people .making-of .mask ul li.current").next().is('li')) {
alert("Exists");
}
else {
alert("Dont exists");
}
Run Code Online (Sandbox Code Playgroud)
DSK*_*pps 14
最简单的方法就是:
if( $( ... ).next('li')[0] ) {
Run Code Online (Sandbox Code Playgroud)
由于jQuery函数总是返回一个jQuery对象,它永远不会等于null.但是访问类似数组的jQuery对象就像使用DOM对象数组一样,因此[0]将拉出第一个匹配的DOM元素或null.检查.length()0也可以.
使用lengthjQuery中的方法:
if($(...).next().length > 0) {
alert("Exists.")
} else {
alert("Doesn't exist!")
}
Run Code Online (Sandbox Code Playgroud)