jQuery plugin:
(function($){
$.fn.extend({
meuPlugin: function(){
$('body').on('click', this, function( e ){
console.log( $(this).attr('href') );
return false;
});
}
});
})(jQuery);
HTML selector:
<a href="um_link_qualquer.php" id="link_teste">Meu link</a>
Plugin Call:
$(document).ready(function(){
$('#link_teste').meuPlugin();
});
Problem:
$(this).attr('href')
is referring to body
, not $('#link_teste')
in the plugin call.
• My first attempt was to change:
$('body').on('click', this, function( e ){
to this.on('click', function() {
(function($){
$.fn.extend({
meuPlugin: function(){
//$('body').on('click', this, function( e ){
this.on('click', function() {
console.log( $(this).attr('href') );
return false;
});
}
});
})(jQuery);
PS: It worked, but not 100%. It turns out that if I assign the plugin to an element that will be loaded later via ajax, the click will not call the plugin.
• I also tried with e.target
, the only difference is that instead of returning body
, returns the clicked element , whatever.
• This is another attempt:
// plugin
$.fn.extend({
meuPlugin: function () {
console.log( this.attr('href') );
return false;
}
});
// chamada do plugin no elemento #link_teste
$(document).ready(function(){
$('body').on('click', '#link_teste', function ( e ) {
e.preventDefault();
$(e.target).meuPlugin();
});
});
It works exactly as it should, but the plugin's call has become very "dirty." I need something more precise and clean as already mentioned:
$('#link_teste').meuPlugin();
Objective:
I need the attributes of #link_teste
referencing it inside the plugin, such as href
, action
, method
, and that is compatible with ajax calls: / p>
$('#link_teste').meuPlugin();
Thank you in advance!