检测jQuery对象是否在页面上 [英] Detect if a jQuery object is on the page or not
问题描述
给定一个jQuery对象, $ j
,我需要知道它是否代表页面上已经存在的东西,或者是否还没有被放在这一页。例如,如果我有这样的话:
Given a jQuery object, $j
, I need to know if it represents something that is already on the page or if it is something that has not yet been put on the page. For example, if I have this:
$j = $('#id-of-something-already-on-the-page');
或
$j = $('<p>Where is pancake house?</p>').appendTo($('#this-is-already-there'));
然后我在页面上有东西,我不需要把它放在页面上。但是,如果我只是这样做:
Then I have something on the page and I don't need to put it on the page. But, if I just have this:
$j = $("<p>I'll cook you some eggs, Margie.</p>");
然后我需要在页面之前附加它。
Then I'd need to append it before it is on the page.
问题是如何在页面上询问 $ j
?我知道两种方式的工作足够好:
The question is how do you ask $j
if it is on the page or not? I know two ways the work well enough:
- 看看它是否有父级:
$ j.parent()长度> 0
意味着它在页面上。 - 看看它是否具有有效的索引:
$ j.index()> -1
意味着它在页面上。
- See if it has a parent:
$j.parent().length > 0
implies that it is on the page. - See if it has a valid index:
$j.index() > -1
implies that it is on the page.
如果 $ j
是 html
或可能 body
;我很高兴忽略这两个病理病例。我不能想到第二种方法会失败的任何方式。
I can see the first one failing if $j
is the html
or possibly body
; I'm happy to ignore those two pathological cases. I can't think of any way that the second approach would fail.
有没有一个标准的技术来询问jQuery对象是否在页面上?我不在乎,如果 $ j
是可见的。
Is there a standard technique for asking if a jQuery object is on the page or not? I don't care if $j
is visible.
推荐答案
,我首先从页面中 中的元素下降,例如< html>
或 ; body>
,并使用 .has()
:
Personally, I'd start by descending from an element you know is in the page, like <html>
or <body>
, and use .has()
:
if ($('html').has($j).length)
{
// $j is in the page
}
甚至对你提到的两个病理病例也是如此。它是更惯用的来检查 .length
,而不是 .size()
。还没有理由检查返回的值是> 0
。 长度
属性将永远为非负整数,因此只需检查该值的真实性即可。
This works even for the two pathological cases you mentioned. It's more idiomatic to check .length
rather than .size()
. There's also no reason to check that the value returned is > 0
. The length
property will always be a nonnegative integer, so it's sufficient to check the truthiness of the value.
这篇关于检测jQuery对象是否在页面上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!