问题
I want my jQuery plugin to behave differently, when called on a $(window) selection. How can I check, if window is in the set? My tries so far:
>>> $(window) == $(window)
false
>>> $(window).is(window)
false
>>> $(window).filter(window).length
0
(Those all work fine for document, by the way.) Of course I can always inspect this[0], but there are edge cases like $('a').add(window) that are not catered by this approach.
I can also filter via function:
>>> $(window).filter(function() { return this === window; }).length
1
but I was hoping for a bit more 'jQuery-ish' or generic approach.
回答1:
You can use index() and pass it the window object. It will return -1 if the window object is not part of the set, or its zero-based index within the set otherwise:
>>> $(window).index(window) >= 0
true
>>> $("a").add(window).index(window) >= 0
true
>>> $("a").index(window) >= 0
false
回答2:
AFAIK, only the $(window).parent() & $(document).parent() return an empty array.
Maybe you can use something like
var test = window
//undefined
$(test).parent().length == 0 && !$(test).is(document)
//true
test = document
//#document
$(test).parent().length == 0 && !$(test).is(document)
//false
回答3:
The .is($(window)) works:
$(window).is($(window)) //true
$('a').add(window).is($(window)) //true
来源:https://stackoverflow.com/questions/11017019/how-can-i-tell-if-window-is-in-a-jquery-set