我正在尝试构建一个插件,该插件将有助于简化客户端上巨大数据的显示,但该插件无法按预期工作。
样品下方:
HTML
<div id="div1" class='test'>
</div>
<div id="div2" class='test'>
编写脚本
(function($) {
var context = $(this);
var methods = {
init: function() {
context.on('click', function() {
console.log(context.attr('id'))
})
}
}
$.fn.sample = function(methodOrOptions) {
context = $(this)
if (methods[methodOrOptions]) {
return methods[methodOrOptions].apply(this, Array.prototype.slice.call(arguments, 1))
} else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
return methods.init.apply(this, arguments)
} else {
$.error('Method ' + methodOrOptions + ' does not exist on jQuery.tooltip')
}
}
})(jQuery);
$(document).ready(function() {
$('.test').each(function(e, ui) {
$(this).sample();
})
})
JSFiddle
在这个示例中,我预计当用户单击第一个div时,它将在控制台中写入div1,当用户单击第二个div时将在控制台上写入div2,然而,控制台正在写入div2。
我的错误是什么?为什么没有按预期工作?
所以这是你试图做的事情的一个非常简单的开始。看看你的想法。。。
(function($) {
$.fn.sample = function () {
//'this' is already a jQuery object since sample is a function of $.fn
//if this does not contain any elements, there's nothing to do
if (!this.length) return;
this.each(function(){
//wrap the iterated element
var $element = $(this);
$element.on('click', function () {
console.log($element.attr('id'));
});
});
}
})(jQuery);
$(function() {
$('.test').sample();
});
您的context
作用域需要修复。只需更改第一部分:
var context = $(this);
var methods = {
init: function() {
context.on('click', function() {
console.log(context.attr('id'))
})
}
}
对此:
var methods = {
init: function() {
var context = $(this);
context.on('click', function() {
console.log(context.attr('id'))
})
}
}
同时删除此行:context = $(this)
我还更新了jsFiddle。