jquery 测试未定义变量或NEXT兄弟的最佳方法?[副本]

14ifxucb  于 2023-06-22  发布在  jQuery
关注(0)|答案(2)|浏览(84)

此问题已在此处有答案

jQuery: Checking if next element exists(7个回答)
7年前关闭。
我想测试一个特定的div后面是否有另一个div,在jQuery中使用.next()。如果它后面确实有另一个div,那么我想调整一些CSS。
我目前正在检查.next() div的CSS,如果不是undefined,则继续进行CSS更改,但我认为这不是一个非常可靠的方法。

var hasNext = $('.slide.active').next().attr('class'); // check the class of the "next" element

if(hasNext !== 'undefined'){
   // There is another slide! Add some arrows
   $('.portfolio .fp-controlArrow.fp-next').css('display','block');
}

首先,这不起作用(尽管console.log显示hasNext = undefined上面的if语句正在通过。
其次我知道这是一种笨拙的做事方式。
你会怎么做基本上:

if (slide with class `active` has a NEXT sibling){
    do this css
}
soat7uwm

soat7uwm1#

只需检查.next()返回的对象的长度,如果没有下一个兄弟,则为0

var hasNext = $('.slide.active').next().length; // check the class of the "next" element

if (hasNext) {//check for truthyness
    // There is another slide! Add some arrows
    $('.portfolio .fp-controlArrow.fp-next').css('display', 'block');
}
nr7wwzry

nr7wwzry2#

应为:

if (typeof hasNext !== 'undefined')

相关问题