如何判断一个元素的上一个或下一个元素是否存在jQuery? [英] how to judge an element's previous or next element exist with jquery?

查看:100
本文介绍了如何判断一个元素的上一个或下一个元素是否存在jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个<ul> :

<ul>
    <li></li>
    <li></li>
    <li class="test"></li>
</ul>

如何判断.test是否具有jquery的下一个元素? 这样吗?:

How can I judge the .test have its next element with jquery ? like this?:

if ($("li.test").next()) { …… }

奇怪的是,即使我这样写:

the strange thing is that ,even I write like above:

if ($("li.test").next()) {alert("true");}

它仍然警告"true",但是如您所见,它旁边没有任何元素?为什么会这样?

it still alert "true",but as you see,there is no element next to it ?why this happened?

或者我能做的就是

        for (i = 0; i < $("li").length; i++) {
            if ($("li").eq(i).hasClass("test")) {
                if (i == $("li").length - 1) {
                    alert("true");
                }
            }
        }

目前这可以解决我的问题,但是有一种简单的方法吗?

presently this could solve my problem,but is there a easy way?

谢谢

推荐答案

jQuery选择将始终评估为布尔值true(如if语句中一样).这是因为它不是本机Javascript类型,而是一个对象.

A jQuery selection will always evaluate to boolean true (as in an if statement). This is because it is not a native Javascript type -- it is an object.

您需要检查所选内容的 length 属性.如果为空,则为0,其值将为false,因此if将不通过.如果不为空,它将是一个正整数,因此将评估为true,因此条件将通过.

You need to check the length property of the selection. If it is empty, this will be 0 and will evaluate to false, so the if will not pass. If it is not empty, it will be a positive integer and will therefore evaluate to true, so the conditional will pass.

if ($("li.test").next().length) { …… }

这篇关于如何判断一个元素的上一个或下一个元素是否存在jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆