简体   繁体   English

同一页面上的多个JQuery插件

[英]Multiple JQuery plugins on same page

I am wondering if there is an easy solution to this: I have the following JQuery plugin created several times on elements defined in a grid 我想知道是否有一个简单的解决方案:我在网格中定义的元素上多次创建了以下JQuery插件

(function ($) {
    $.fn.MyPlugin = function () {

        $(this).mouseenter(function () {
           //do something for single plugin instance
        });
    };

})(jQuery);

However, how can I go about uniquely identfying which plugin instance I am triggering the mouse enter function on. 但是,我该如何唯一地标识触发鼠标输入功能的插件实例。 With the current setup I am referencing all the instances, but I want to only trigger the mouseenter for one of them at the time. 在当前设置下,我引用了所有实例,但是我只想同时触发其中一个的mouseenter。

The plugin is created like this: 插件是这样创建的:

$(".someClass").MyPlugin(); 

You don't need to create a plugin mutiple times, that's why it's called a plugin. 您无需多次创建插件,这就是为什么它被称为插件。 You just plug it in wherever you want. 您只需将其插入所需的任何位置。 Take a look at the jquery plugins authoring page on how to start coding a plugin. 查看有关如何开始编码插件的jquery插件创作页面 It provides some nice templates. 它提供了一些不错的模板。

In your code $(this) is redundant, since this is already a jQuery object. 在您的代码中$(this)是多余的,因为this已经是一个jQuery对象。 Then, you'd want to always return this to maintain chainability in your plugin. 然后,您希望始终return this以保持插件中的可链接性。 You can use $(this) inside the mousenter event to reference the current element being processed by the plugin in the DOM. 您可以在mousenter事件中使用$(this)来引用DOM中插件正在处理的当前元素。

Sometimes it's also useful to return this.each() and loop each element and do something. 有时return this.each()并循环每个元素并执行某些操作也很有用。 In this case, since you're attaching an event it doesn't help because an event works on every item in the collection of items; 在这种情况下,由于要附加一个事件,所以它无济于事,因为事件适用于项目集合中的每个项目。 in this case, this refers to the collection on which you called the plugin: 在这种情况下, this指的是调用了该插件的集合:

$.fn.MyPlugin = function () {

    return this.mouseenter(function () {
       $(this).something();
       //do something for single plugin instance
    });

};

Then you'd call the plugin like so: 然后,您将这样调用插件:

$('elements').MyPlugin();

Just call the plugin on the element(s) that you want and those elements will have the mouseenter event attached. 只需在所需的元素上调用插件,这些元素将附加mouseenter事件。

what is the html where you are using the plugin? 您在哪里使用HTML插件? mouseenter can be connected to an element id so instead of calling (this).mouseenter, call the div by id (ie $("div.somediv").mouseenter(function(){ .... what you want to do ..... } mouseenter可以连接到元素id,因此不必调用(this).mouseenter,而是通过id调用div(即$(“ div.somediv”)。mouseenter(function(){....)。 ....}

the jquery site shows an example of using multiple mouse events for nested divs. jQuery站点显示了对嵌套div使用多个鼠标事件的示例。

http://api.jquery.com/mouseenter/ http://api.jquery.com/mouseenter/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM