...">

Click event not working properly in jQuery plugin

I am writing a jQuery plugin, but I have 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');
 });

... is displayed here. I don’t understand why this is happening because $ root and $ ('# trac') are exactly the same jQuery object.

How can i fix this?

Thank!

+5
source share
2 answers

The ".live ()" function needs a selector, and you do not give it in your plugin. The jQuery object you create ( $(this)) is a valid object, but there is no selector string.

:

  $root.click(function() { ... });

: : "... $root $('# trac') ". , . jQuery , . , "$ root" "$ (this)". ".live()" , <body>, , .

+8

, "" , - , , , :

<div id="mystuff">hi</div>
<div id='answer'>empty</div>

$.fn.myplugin = function() {
    this.live('click', function() {
        $('#answer').text('here');
    });
}
$('#mystuff').myplugin();

: http://jsfiddle.net/FgUEB/, , "this" , " ", - .each - , , ( , ) , , .each you .

jQuery.fn.newMethod = function(){
    return this.each(function(){
        alert(typeof this);
    });
};

( ) HTML. jQuery, jQuery ( jQuery, jQuery ().

jQuery.fn.newMethod = function(){
    return this.each(function(){
        jQuery(this).css({'background-color':'red'});//each inner element
    });
};
0

All Articles