Jquery-访问插件的所有实例

Jquery - access to all instances of a plugin

本文关键字:实例 访问 插件 Jquery-      更新时间:2023-09-26

我正在开发一个jquery插件"myPlugin",它可以做一些图形化的事情。它运行良好,我对此感到高兴。

(function ( $ ) {
    $.fn.myPlugin = function(params) {
        /* some code */
        $(this).focus(function() {
            /* draw things */
        });
    };
}( jQuery ));

我这样称呼它:$("#foo").myPlugin();

一切都很好:每次元素获得焦点时,插件都会被触发,绘制出一些很酷的东西。插件包含一个私有函数end,我最终可以通过函数close 从外部访问它

(function ( $ ) {
    $.fn.myPlugin = function(params) {
        /* some code */
        $(this).focus(function() {
            /* draw things */
        });
        function end(){
            /* destroy the draw */
        }
        return{
             close: function() { end(); }
        }
    };
}( jQuery ));

这个功能允许我"从外部"关闭插件。

var bar = $("#foo").myPlugin();    // create the graphic
bar.close();                       // destroy the graphic for this element

一切仍然很好!但现在,我有一个问题:我想访问所有的插件。假设我需要创建一个随机数:

var bar1 = $("#foo1").myPlugin();
var bar2 = $("#foo2").myPlugin();
var bar3 = $("#foo3").myPlugin();

我希望当一个元素获得焦点(并开始绘制(时,它确实会破坏所有其他现有的元素:

何时:

$("#foo1").focus();    // make the draw

它也这样做:

bar2.close();    // destroy an eventual draw of #foo2
bar3.close();    // destroy an eventual draw of #foo3

在这里。。。我被阻止了如何访问我的插件的所有内容我想把所有的var名称(bar1,bar2,bar3,…(保存在某个地方,以便访问它,但我无法通过插件获得它们。或者最终创建第二个中间插件,该插件将启动myPlugin并存储名称。。。我很困惑。有什么想法吗?

干杯<3

You can do something like this
(function ( $ ) {
    $.fn.myPlugin = function(params) {
        /* some code */
        $(this).focus(function() {
        //clear previous things
        $('.myplugin').parent().remove()// or remove your markings
        //append
        $(this).append('<div class=".myplugin"></div>')
        /* draw things */
        });
        function end(){
            /* destroy the draw */
        }
        return{
             close: function() { end(); }
        }
    };
}( jQuery ));

u聚焦时清除所有此类div父级或标记在插件id 中添加一个临时div