I’m writing a jQuery plugin, but I’m having a problem:
My HTML element
<a id="trac"></a>
My JS that calls the plugin
$('#trac').myplugin();
My plugin
$.fn.myplugin = function(){
var $root;
return this.each(function(){
$root = $(this);
$root.live('click',function(){
console.log('here');
});
});
}
It happens that “here” is never displayed.
But if I use…
$('#trac').live('click',function(){
console.log('here');
});
…”here” is displayed.
I don’t understand why it is happening because $root and $(‘#trac’) are exactly the same jQuery object.
How can I fix it?
Thanks!
The “.live()” function needs a selector, and in your plugin you’re not giving it one. The jQuery object you build (
$(this)) is a valid object but there’s no selector string involved.You could directly bind the handler:
To elaborate: you say, “… because $root and $(‘#trac’) are exactly the same.” The problem is that that is not really true. When you build a jQuery object with a selector string, the object keeps that selector string around. There’s no string when you build “$root” from “$(this)”. The “.live()” function operates by creating a handler on the
<body>element and then testing the target of each event that bubbles up against that selector.