我正在尝试构建一个有助于简化客户端大量数据显示的插件,但该插件无法按预期工作。
以下示例:
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();
})
})
在这个示例中,我预计当用户点击第一个div时,它将在控制台div1中写入,当用户点击第二个div时,div2将写在控制台上,但是,控制台正在编写div2
我的错误是什么?为什么它没有按预期工作?
答案 0 :(得分:1)
所以这是你想要做的事情的一个非常简单的开始。看看你的想法......
(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();
});
答案 1 :(得分:0)
您的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。