在JavaScript或Jquery中测试对象的祖先/后代关系 [英] Testing objects for ancestor/descendent relationship in JavaScript or Jquery

查看:86
本文介绍了在JavaScript或Jquery中测试对象的祖先/后代关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图想出一个可重用的JS或jQuery函数,这将允许我测试一个对象是否是另一个对象的DOM后代。



我看过一个测试模型,

  $ b .parents('nodename')。length> 0 

当您只需要检查一个元素是该名称的任何节点的子节点。



但是一个特定节点呢?你不能测试

  $ b.parents($ a).length> 0 


作为一个很少的背景,我试图测试文档点击事件的目标是否是特定对象的子对象。例如,如果event.target是$ b的子代,则返回true,否则返回false。但是这个函数可能会在以后有其他的影响。



谢谢!

解决方案

p>在使用jQuery对象的jQuery祖先我建议

  if($(obj1).parents()。index($(obj2))> = 0){
// obj1 obj2的后代
}


I'm trying to come up with a reusable JS or jQuery function that would allow me to test if one object is a DOM descendant of another.

I've seen a model of testing for

$b.parents('nodename').length>0

Which is fantastic when you only need to check if an element is a child of any node by that name.

But what about a specific node? You can't test

$b.parents($a).length>0

Because jQuery parents takes a nodename expression as an argument to filter.

As a little background, I'm trying to test if a document click event's target is a child of a specific object. For instance, if the event.target is a child of $b, return true, otherwise, return false. But this function could have other implications later on.

Thanks!

解决方案

In jQuery ancestors using jQuery objects I suggested

if ($(obj1).parents().index($(obj2)) >= 0) {
    // obj1 is a descendant of obj2
}

这篇关于在JavaScript或Jquery中测试对象的祖先/后代关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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