【发布时间】: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