Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
714 views
in Technique[技术] by (71.8m points)

how to judge an element's previous or next element exist with jquery?

suppose I have an <ul> :

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

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");}

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

Or what I can do is

        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?

thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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) { …… }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...