【问题标题】:jQuery; Check if object has child $(this)jQuery;检查对象是否有子 $(this)
【发布时间】:2011-09-25 17:19:37
【问题描述】:

我想知道如何以最好的方式查看容器 div 是否包含子元素。我有一个点击事件触发 div id=unread 或 div id=read 的孩子。我想看看这个孩子在哪里。

我的想法是这样的:

if ($("#unread").find($(this)))
    alert("unread");
else
    alert("read");

编辑: $(this) 是 #unread 或 #read 两个级别的后代。

问候

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

利用:.children()

if( $("#unread").children().length > 0)
    alert("unread");
else
    alert("read");

编辑

if($(event.target).closest('#unread').length > 0)
    alert('unread');
else
    alert('read');

【讨论】:

  • 哦,我忘了说 $(this) 是 #unread 或 #read 两个级别的后代。所以这个父级的父级应该是未读或已读
  • 这行不通,因为点击的 $(this) 是 #unread 的两个级别。它也不是来自#unread 的两个级别的独生子女。
【解决方案2】:

我认为只需添加 .length 就可以了:

if ($("#unread").find($(this)).length > 0)
    alert("unread");
else
    alert("read");

【讨论】:

  • 有多个看起来像 $(this) 的孩子,即 #unread 或 #read 的两个级别。因此,我猜孩子们不会识别 $(this)。
  • 这没有回答问题:OP 询问如何检查一个 div 是否是另一个 div 的(孙)子,而不仅仅是检查一个 div 是否有任何子。
  • @nnn- 是的,现在它说
  • it always 说:第二句和第三句以及示例代码明确了click事件在后代div上,问题是如何找出哪个祖先它属于;编辑只是澄清了这种关系正好相隔两代。
【解决方案3】:

使用.closest().parents() 从点击的元素向上搜索树:

if ($(this).closest("#unread").length == 1)
   // etc

否则,您对非 jQuery 答案感兴趣吗?鉴于您已经说过带有点击事件的 div 恰好比“已读”或“未读”的 div 低两个级别,您可以这样做:

if (this.parentNode.parentNode.id === "unread")
   alert("unread");
else
   alert("read");

// or just alert(this.parentNode.parentNode.id);

【讨论】:

    【解决方案4】:

    使用closest$(this) 向后查找#unread 作为祖先:

    if($(this).closest('#unread').length > 0)
        alert('unread');
    else
        alert('read');
    

    根据您的 HTML 结构,这将比搜索 #unread 的所有子代以找到 this 更快。虽然速度差异可能并不那么重要,但您应该知道倒退的选择以及这样做可能带来的好处。

    检查祖先可能更符合您的意图:您手头有this,而您真正想知道的是“它在#unread 内吗?”。使用closest 回溯 DOM 树与您提出的问题完全匹配。

    如果出于某种原因,您一心想要从#unread 开始并查看其后代,那么您可以使用find

    if($('#unread').find(this))
        alert('unread');
    else
        alert('read');
    

    但这种方法只有在您至少使用 jQuery 1.6 时才有效。

    【讨论】:

      【解决方案5】:

      我想知道如何以最好的方式查看容器 div 是否包含子元素。

      使用$.contains(),尤其是在性能受到关注的情况下。来自文档:

      jQuery.contains(容器,包含)

      返回:布尔值

      描述: 检查一个 DOM 元素是否是另一个 DOM 元素的后代。

      正如其他人所推荐的那样,它比 .find().children().closest() 更有效。但是请注意,它只接受 DOM 元素作为参数,而不接受 jQuery 对象(这是其性能更好的部分原因)。

      在您的情况下,您可以在单击事件处理程序中执行此操作:

      if ($.contains($("#unread")[0], this)) {
          alert("unread");
      } else {
          alert("read");
      }
      

      编辑: 再次考虑这一点,从被点击的元素向上搜索可能更直观,而不是从父元素向下搜索,而且点击的性能通常不会成为问题事件处理程序。也就是说,我会选择使用.closest() 方法(正如@nnnnnn 和@mu 所建议的那样),所以我的点击事件处理程序将包含:

      if ($(this).closest("#unread").length > 0) {
          alert("unread");
      } else {
          alert("read");
      }
      

      【讨论】:

        猜你喜欢
        • 2010-12-23
        • 1970-01-01
        • 2018-09-10
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多