如何在jQuery中检查元素是否在另一个元素中? [英] How can I check if an element is within another one in jQuery?

查看:103
本文介绍了如何在jQuery中检查元素是否在另一个元素中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript或jQuery中是否有任何直接的方法来检查元素是否在另一个元素中。

Is there any direct way in JavaScript or jQuery to check if an element is within another one.

我不是指 $(this).parent 因为我希望找到的元素可以是元素树中较低的随机数。

I'm not referring to the $(this).parent as the element I wish to find can be a random number steps lower in the tree of elements.

作为例如,我想检查< div id =THIS DIV> 将在< div id =THIS PARENT>

As an example, I would like to check if < div id="THIS DIV"> would be within < div id="THIS PARENT">:

<div id="THIS_PARENT">
 <div id="random">
  <div id="random">
   <div id="random">
    <div id="THIS_DIV">
(... close all divs ...)

所以伪代码:

 if($("div#THIS_DIV").isWithin("div#THIS_PARENT")) ...

如果没有任何直接方式我可能会为此做一个功能,但仍值得问。

If there isn't any direct way I'll probably do a function for this but still it's worth asking.

推荐答案

你可以这样做:

if($('#THIS_DIV','#THIS_PARENT').length == 1) {

}

通过指定搜索的上下文(第二个参数)我们基本上是说在ID为的元素中查找ID为 #THIS_DIV 的元素#THIS_PARENT 。这是使用jQuery实现它的最简洁方式。

By specifying a context for the search (the second argument) we are basically saying "look for an element with an ID of #THIS_DIV within an element with ID of #THIS_PARENT". This is the most succint way of doing it using jQuery.

我们也可以这样写,使用 查找 ,如果它对您更有意义:

We could also write it like this, using find, if it makes more sense to you:

if($('#THIS_PARENT').find('#THIS_DIV').length == 1) {

}

或者像这样,使用 父母 ,如果您想从孩子向上搜索:

Or like this, using parents, if you want to search from the child upwards:

if($('#THIS_DIV').parents('#THIS_PARENT').length == 1) {

}    

其中任何一个都可以正常工作。 长度位是必要的,以确保搜索的长度> 0.我当然会建议你选择第一个,因为它是最简单的。

Any of these should work fine. The length bit is necessary to make sure the length of the "search" is > 0. I would of course personally recommend you go with the first one as it's the simplest.

另外,如果您通过ID引用元素,则不必(尽管当然完全可以)在选择器前面添加标签名称。但就速度而言,它并没有真正帮助,因为jQuery将在内部使用本机 getElementById()。使用标记名称仅在按类选择时很重要,因为 div.myclass 远远快于 .myclass 如果只有< div> 元素将具有特定的类。

Also, if you are referring to an element by ID it's not necessary (although of course perfectly okay) to preface the selector with the tag name. As far as speed, though, it doesn't really help as jQuery is going to use the native getElementById() internally. Using the tag name is only important when selecting by class, as div.myclass is much, much faster than .myclass if only <div> elements are going to have the particular class.

这篇关于如何在jQuery中检查元素是否在另一个元素中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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