简体   繁体   中英

Jquery - How to defined user defined jquery function?

Can we create user defined function in jquery like :

    $(selector).click(function()
   {

    })

Above function is already in jquery library.

if i want to create function like above one For eg :

$(selector).demo();

How i can create function "demo()" to which i can prefix the selector as $(selector).demo();

So:

jQuery.fn.newfunction= function() {

//code goes here

};

And then call:

$(element).newfunction();

jQuery.fn.extend()

by jQeury.fn.extend()

jQuery.fn.extend({
    demo: function(value){
       alert(value);
    }
});

you can also pass parameters if you need, like 10 in this example.

$(selector).demo(10);

if you would like to pass a function

$.fn.extend({
        demo: function(func){
            if(typeof func === 'function')
                func();
        });

pass the function then you trigger it in demo

  $(selector).demo(function(){
      alert('test');
  });

hope it will help you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM