如何检查jQuery插件是否已绑定到DOM节点? [英] How can you if check a jQuery plugin is already bound to a DOM node?

查看:62
本文介绍了如何检查jQuery插件是否已绑定到DOM节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数jQuery插件在首次初始化时都绑定/绑定到DOM节点.

Most jQuery plugins are tied/bound to a DOM node when you first initialize them.

$('#foo').bar({options: ...});

如何检查当前绑定到#foo之类的DOM节点的插件或对象是什么?

How can you check to see what plugins or objects are currently bound to a DOM node like #foo?

if($('#foo').bar)
if($.inArray('bar', $('#foo').eq(0)))
if($('#foo').eq(0).indexOf('bar'))
if($('#foo').hasOwnProperty('bar'))

例如,可以将事件绑定到这样的对象上

For example, it's possible to get the events bound to an object like this

console.log($('#foo').data('events'));

推荐答案

除非插件本身定义了某种方法来更改其正在处理的元素,否则是不可能的.例如:

Unless the plugin itself defined some way of altering the element(s) it's working on, it's not possible. For example:

$.fn.extend({
  foo: function() { console.log("I am foo!"); }
});

$('#bar').foo();

在这里,我定义了一个完整的(好了,少了一点)的jQuery插件,它甚至没有尝试与其调用元素进行交互.尽管如此,您仍可以根据需要在任何jQuery封装的元素集合上使用它,因为由于这一行(jquery.js),任何jQuery封装的元素集合 在其原型中都具有此方法. :

Here I defined a complete (well, more-o-less) jQuery plugin which doesn't even try to interact with its calling element. Still, you can use it as you wish, on any jQuery-wrapped collection of elements, as any jQuery-wrapped collection of elements has this method in its prototype because of this line (from jquery.js):

jQuery.fn = jQuery.prototype = { ... }

...在调用$.fn.extend插入该插件之后,没有双关语.

... after $.fn.extend was called to plug in that plugin, no pun intended.

但是,即使要求我的插件以某种方式更改其调用元素,也是如此:

But even if my plugin were required to change its calling element in some way, like this:

$.fn.extend({
  bar: function() { this.html('I am all bar now!'); }
});
$('#bar').bar();

...基本上,我仍然需要通过一些外部事件(DOM突变事件)来处理此问题,而不仅仅是依赖于一些内部jQuery日志记录.

... I would still need to, basically, handle this with some external events (DOM Mutation ones), and not just depend on some internal jQuery logging.

这篇关于如何检查jQuery插件是否已绑定到DOM节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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