Reputation: 45
Check here jsfiddle
$(function(){
$.fn.my_alert = function(){
var base = this;
base.init = function() {
base.on('click',function(e) { base.onClick(); });
}
base.onClick = function(){
alert(base.attr('data-id'));
}
base.init();
}
});
$(document).ready(function(){
$('.myalert').my_alert();
});
When I click on any button it alerts the data-id attribute of the first button,
but I need it to instead show the data-id attr of the clicked button..
Upvotes: 0
Views: 31
Reputation: 318182
The issue is the use of base
inside the click handler, where you should be using this
instead as base
is all the matching elements the plugin was attached to, not just the clicked element.
You should be doing it like this instead, dropping the base
variable, and returning this.each(...
to make it chainable
$(function() {
$.fn.my_alert = function() {
return this.each(function() {
$(this).on('click', function(e) {
alert( $(this).data('id') );
});
});
}
});
Upvotes: 2