如何使用jQuery检查DOM相等性? [英] How to check for DOM equality with jQuery?

查看:97
本文介绍了如何使用jQuery检查DOM相等性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是在构建一个简单的列表,然后选择列表中的一项.我可以通过将"selected"类应用于我想要选择的任何项目来实现此目的.我有两个前进和后退按钮,遍历此列表.但是,当用户到达列表中的第一个或最后一个元素时,我要回发帖子.这是我遇到的问题,因为我无法确定当前选择的项目不是第一个还是最后一个.

I'm basically building a simple list, and one of the items in the list is selected. I'm accomplishing this by having a "selected" class applied to whichever item I want to have selected. I have two buttons that go forward and backward which traverse this list. However, when the user gets to the first or the last element in the list, I want to do a post back. This is where I'm stuck, because I'm having trouble identifying that the currently selected item is not the first or the last.

简单示例:

<div id="list">
    <p>item 1</p>
    <p>item 2</p>
    <p class="selected">item 3</p>
</div>

假设用户按下了下一个按钮,这时我正在检查与此类似的内容:

Let's say the user presses the next button, at this point I'm checking for something similar to this:

if (jQuery('#list p.selected') == jQuery('#list p:last-child'))
    //do post back

但是,这种逻辑返回的是false,这使我相信我正在以错误的方式进行处理.

However, this logic is returning false, which leads me to believe I'm approaching this the wrong way.

对我来说,使用jQuery检查这种逻辑的最佳方法是什么?

What is the best way for me to check for this kind of logic using jQuery?

推荐答案

尽管您可以比较Matt所显示的jquery对象,也可以简单地与索引运算符进行比较

Although you can compare jquery objects as Matt has shown, or simply with index operator

if($("#list p.selected")[0] == $("#list p:last-child")[0])...

jQuery很少需要此功能.有一种更好的方法!

this is rarely needed with jQuery. There is a better way!

if($("#list p.selected").is(":last-child"))....

反之亦然,更具可读性

if($("#list p:last-child").is(".selected"))....

这篇关于如何使用jQuery检查DOM相等性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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