开发者

How do you handle click events inside a jQuery plugin?

How do you handle click events inside a plugin? A simplified description is that I want to have a plugin that will detect a click and then update another element.

Example Usage:

$("#some_id").myPlugin("another_id");

Example Plugin:

(function($){

     $.fn.myPlu开发者_JS百科gin=function(update_id){

     .click({$(update_id).html("content_upated");});

     }

})(jQuery);

I don't understand how to code the .click event inside the plugin. Any examples would be helpful. Thanks.


You should do two things:

  1. Use this to reference the elements to which your plugin is being applied
  2. Namespace your events, so they can easily be unbound later

Try the following

(function($){

     $.fn.myPlugin = function(update_id) {

       this.bind("click.myPlugin", function () {
         $(update_id).html("content_upated");
       });

    };

})(jQuery);

You should read the page on jQuery plugin authoring for more information on how to correctly develop jQuery plugins. You're missing other important details like accepting an arguments object.


Use this to access the object that the plugin is being invoked on:

(function($){
     $.fn.myPlugin=function(update_id){
         this.click( function() { $(update_id).html("content_upated"); } );
     }
})(jQuery);

Note that your usage would need to include the id selector in this example, or you would need to include it in your click function:

$("#some_id").myPlugin("#another_id");


You would invoke .each() to iterate over the matched elements, or you can attach via regular jQuery method.

(function($)
{
     $.fn.myPlugin = function(anotherIdentifier)
     {
          // this.click is equivalent to $(identifier).click()
          this.click(function()
          {
              // Thing to do
          });
     };
})(jQuery);


(function($){
     $.fn.myPlugin=function(update_id){
         this.click(function(){ $(update_id).html("content_upated"); });
     }
})(jQuery);

Make sure update_id is a valid selector.


(function($){   
     $.fn.myPlugin=function(update_id){ 
         this.click(function(){ $(update_id).html("content_upated"); });
     }
})(jQuery);

Make sure update_id is a valid selector.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜