【发布时间】:2016-08-25 22:44:41
【问题描述】:
我正在构建一个插件,我们称之为ptest,我希望能够使用以下方式调用它:
$(".myClassName").ptest();
由于我使用的是调用插件的元素中的属性,假设data-attribute 我现在知道返回this.each(...); 是必须。
这是我的代码:
(function($){
var op;
$.fn.ptest = function(options) {
op = $.extend({
target: null,
attribute: null
}, options);
return this.each(function(){
op.target = $(this);
op.attribute = op.target.attr("data-attribute");
bind();
});
};
function bind(){
op.target.find('.clickable').bind('click',log);
}
function log(){
console.log(op.attribute);
}
}(jQuery));
我知道通过将op 作为全局变量,它将始终保留attribute 和target 的最后一个值。如何使 op 变量为 .myClassName 的每个元素保留正确的值,同时能够从 log 或 bind 函数访问每个 op?
我觉得我需要以不同的方式声明函数和变量,但是如何?
我看过很多不同的问题和教程,这里有一些:
【问题讨论】:
-
你用
bind和log做什么? -
@T.J.Crowder 在我的问题中我只留下了基本代码,在真正的代码中我使用
op.attribute来查询数据库,所以我需要每个属性都是正确的 -
恕我直言,这并不能真正回答问题。
-
@T.J.Crowder 你能更好地描述你想知道的吗?
-
op.target.find('.clickable').bind('click',log);绑定点击事件触发log
标签: javascript jquery plugins