【问题标题】:Check whether element in a list is the first检查列表中的元素是否是第一个
【发布时间】:2014-06-24 15:30:36
【问题描述】:

我有一个列表,我正在使用 jQuery 来删除列表对象。

$(document).off('click', '#delete').on('click', '#delete',function(e) {
    $(this).parent().remove();
}); 

我想知道如何判断要删除的元素是否是列表中的第一个?

【问题讨论】:

  • ID 必须是唯一的。因此,如果#delete 超过 1 个,则您的 HTML 无效。
  • @Karl-AndréGagnon 啊,是的,谢谢。我现在会解决这个问题。

标签: jquery dom-manipulation


【解决方案1】:

您也可以使用.index() 位置。这个函数返回一个从零开始的索引,所以对于第一个元素,你得到 0。另一个有趣的点是,在 javascript 中,0 是 false,所有其他数字都是 true。然后,如果元素是第一个元素,.index() 函数将返回 false

$(document).off('click', '#delete').on('click', '#delete',function(e) {
    if(!$(this).parent().index()){
        //the element is the first element
    }
});

This is the full DOC for the .index() function.

【讨论】:

  • 此解决方案可行,但 IMO 条件的可读性受到影响。
【解决方案2】:

您可以使用is:first

所以应该是这样的:

if($(this).parent().is(':first')) {
    // this was the first element
}

【讨论】:

  • 你怎么知道第一项是当前的?
  • 我编辑了我的答案。他在他的示例中删除的是$(this).parent(),所以只需检查它是否是第一个。
  • 这将始终返回 true。 this 是单个元素。 parent 返回 1 个元素。 :first 检查它是否是 jQuery 对象的第一个。
  • @Karl-AndréGagnon 我只是在使用提出问题的人正在删除的元素,那就是$(this).parent()
  • @edhedges 可以重用代码,但 is(':first') 部分是错误的,因为它总是返回 true。当 jQuery 堆栈中只有 1 个元素时,该元素总是第一个。
【解决方案3】:

您可以使用is 方法:

if ($(this).parent().is(':first-child'))
{
}

Documentation

【讨论】:

  • 这与他要删除的元素不同。看我的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-24
  • 1970-01-01
  • 2022-01-06
  • 2012-08-01
  • 1970-01-01
  • 2021-12-07
相关资源
最近更新 更多