【问题标题】:Give jQuery plugin access to selected DOM objects让 jQuery 插件访问选定的 DOM 对象
【发布时间】:2025-12-01 14:05:01
【问题描述】:

我正在尝试为 jQuery 编写一个不遵循他的文档中概述的模式的插件:http://docs.jquery.com/Plugins/Authoring

如下:

(function( $ ){

$.fn.insert = {
    'hello': function(text){ 
        $(this).text(text); 
    },
    'goodbye': function(){
        alert('goodbye');
    }
}
})( jQuery );

页面使用以下代码实例化此插件:

$(document).ready( function(){
    $('#test').insert.goodbye();
    $('#test').insert.hello('blahblahblah');
});

在这种形式中,.goodbye() 确实初始化正确,但很明显,.hello() 不正确。在 firebug 中检查 this 时,它显示了属于其包含函数的范围。 (提示手掌)。

如何让 'hello' 中的函数访问选定的 DOM 对象?我对讨论为什么或为什么不应该以这种方式创建插件并不感兴趣。对我来说,这更像是一种学术练习。

附:我还应该注意,当hello() 部分尝试运行时出现此错误:doc.createDocumentFragment is not a function

更新

(function( $ ){

$.fn.insert = {
    'el': this,
    'hello': function(text){ 
        $(this.el).text(text); 
    },
    'goodbye': function(){
        alert('goodbye');
    }
}

})( jQuery );

对代码进行了此更新。仅供参考,Firebug 确实显示 this.el 引用了有问题的 DOM 对象,而 text 仍然携带传递的字符串,但它仍然没有将文本插入到元素中,并且仍然给我上述错误。

【问题讨论】:

  • 当我运行这个时,this.el 引用了全局对象(窗口)

标签: javascript jquery dom plugins


【解决方案1】:

我不确定……但这可行:

<html>

    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
        <script>

            (function($){

                $.fn.myinsert = function(){

                    this.hello = function(text){ 
                        $(this).text(text);
                    };

                    this.goodbye = function(){
                        alert('goodbye');
                    };

                    return this; //this is the gotcha

                };

            })(jQuery);

            $(function(){
                var test = $('#test');
                test.myinsert().goodbye(); 
                test.myinsert().hello('heyo');
            });

        </script>
    </head>

    <body>

        <div id="test">My name is</div>

    </body>

</html>

【讨论】:

  • test.myinsert.goodbye(); 本身确实会触发,所以我知道您可以从对象中调用方法。我什至能够实现一种基本的方法来获取具有附加属性的引用元素:'el': this,,但是,我仍然无法触发 hello 方法。
  • 非常感谢!完美运行。顺便说一句,我发现通过在每个方法中返回this,您还可以从插件链接!是不是很棒!?
【解决方案2】:

您已将“插入”定义为位于 jQuery 对象上的对象,而不是可以在选择时调用的函数。我认为您永远无法通过这种方式获得当前选择的范围。您可以成功调用 goodbye(),因为它不依赖任何上下文/范围来执行。

【讨论】: