How can I tell, if window is in a jQuery set?

故事扮演 提交于 2020-01-04 04:26:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!