gpt4 book ai didi

javascript - jQuery - 插件方法调用

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:27:04 28 4
gpt4 key购买 nike

我正在尝试根据一些官方 best practices 创建一个 jQuery 插件

(function($){

var methods = {
init : function( options ) {
this.options = options;
}
, add_that: function (elem) {
this.append(elem);
return (this);
}
, add_this: function (elem) {
return (methods.add_that(elem));
}
};

$.fn.test = function (method) {
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.test' );
}
};

})(jQuery);

我希望 add_that 方法能够将内容附加到匹配的元素。
现在从 add_this 调用此方法。

$('#test').test('add_this', $('<div />'));

TypeError: this.append is not a function

为什么我不能从 add_that 访问插件 (this)?

最佳答案

因为当您从 add_this 调用它时范围已经改变。请注意,原始调用使用 Function.apply 将调用范围限定为 this

if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
}

因此您大概可以通过在您的方法中再次使用 apply 来解决这个问题:

add_this: function (elem) {
return methods.add_that.apply(this,[elem]);
}

实例:http://jsfiddle.net/XaUHV/

关于javascript - jQuery - 插件方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9537293/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com