在JavaScript或Jquery中测试对象的祖先/后代关系

编程入门 行业动态 更新时间:2024-10-25 02:28:49
本文介绍了在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中测试对象的祖先/后代关系

本文发布于:2023-10-28 00:52:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535019.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:祖先   后代   对象   关系   测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!