为所选DOM对象提供jQuery插件访问权限

时间:2011-04-29 20:04:54

标签: javascript jquery dom plugins

我正在尝试为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时,它显示了属于其包含函数的范围。 (提示facepalm)。

如何让'hello'内部的函数访问所选的DOM对象?我真的不想讨论为什么或为什么不应该以这种方式创建插件。这对我来说更像是一次学术练习。

P.S。我还应该注意,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仍然传递了传递的字符串,但它仍未将文本插入元素中,并且仍然给我上述错误。

2 个答案:

答案 0 :(得分:3)

我不确定......但这有效:

<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>

答案 1 :(得分:0)

您已将“insert”定义为坐在jQuery对象上的对象,而不是可以在选择上调用的函数。我不认为你能够以这种结构方式获得当前选择的范围。您可以成功调用goodbye(),因为它不依赖任何上下文/范围来执行。