【问题标题】:How to tell if an object is $(document) inside a jQuery function?如何判断一个对象是否是 jQuery 函数中的 $(document)?
【发布时间】:2013-03-22 22:41:48
【问题描述】:
$.fn.foo = function() {
    console.log($(this));
};

$("#foo").foo();

$(document).foo();

如何判断函数内的天气$(this)是否为$(document)


this question,有人建议

1. if (obj instanceof HTMLDocument)

2. if (Object.prototype.toString.call(obj) == "[object HTMLDocument]")

3. $obj.is('html')

但它们都不起作用。

【问题讨论】:

  • 是的,这就是我要证明的,但声明 $(this) == $(document) 返回 false
  • 这行不通。即使$(document) == $(document) 也会导致错误,因为它们是两个不同的对象。
  • 不,$(this) 是 jquery 对象,this 不是
  • @DavidFregoli 在这里阅读 - this 是一个 jQuery 对象 docs.jquery.com/Plugins/Authoring#Context
  • 抱歉没有注意到它在扩展 $。然后就这样做[0] == 文档

标签: jquery object document


【解决方案1】:

那么简单...

if (this[0] === document)

... as this 在 jQuery 函数中对应于 jQuery 对象(不是 HTML 对象)。即使这个对象是空的,this[0] 仍然是一个有效的表达式——它只是undefined

另一种方法是使用 jQuery is 方法:

if ($(this).is(document))

... 因为它也接受DOMElement 作为参数。

【讨论】:

  • +1 看到你有正确的答案,所以我等了.. 但是如果 this 在 jQuery 函数中,则不需要包装
【解决方案2】:
$.fn.foo = function() {
    console.log(this[0] == document);
};

$("#foo").foo();

$(document).foo();

【讨论】:

  • 也许你下次应该打字快点。但无论如何,谢谢。 :)
猜你喜欢
  • 2012-10-16
  • 1970-01-01
  • 2015-03-01
  • 2019-02-11
  • 1970-01-01
  • 2011-11-28
  • 1970-01-01
  • 2018-05-06
相关资源
最近更新 更多