Create function in jquery

I am trying to make a jquery function and use the code below, but not getting any output. Please tell me how to do this.

<script type="text/javascript"> (function($){ $.fn.myplugin = function(){ alert(this.id); }; })(jQuery); $("#sample").myplugin(); </script> 
+7
source share
5 answers

Here you can see the working code - http://jsfiddle.net/gryzzly/YxnEQ/

Please note that you need an element with the identifier "sample" that will be present in your document when you run the above code. In addition, this points to a jQuery object, so to get the identifier of the elements, you need to use one of the following values:

 alert( this[0].id ); 

or

 alert( this.attr('id') ); 

The first is preferable because it is faster.

+11
source

Try the following:

 <script type="text/javascript"> $(document).ready(function(){ myplugin($("#sample")); }); function myplugin(obj){ alert(obj.id); } </script> 
+5
source

Try the following:

 <script type="text/javascript"> $(document).ready(function(){ $("#sample").myplugin(this.id); }); function myplugin(id) { alert(id); } </script> 
+3
source

Try to change

  alert(this.id); 

to

  alert(this[0].id); 

How do you get an array of jQuery objects.

+1
source
 alert(this.attr('id')); 

this in this context is a jQuery object, not a raw DOM element.

0
source

All Articles