How to create a jQuery function (a new jQuery meth

2019-01-01 12:24发布

I know that in JavaScript the syntax is as follows:

function myfunction(param){
  //some code
}

Is there a way to declare a function in jQuery that can be added to an element? For example:

$('#my_div').myfunction()

13条回答
还给你的自由
2楼-- · 2019-01-01 12:35

You can always do this:

jQuery.fn.extend({
   myfunction: function(param){
       // code here
   },
});
OR
jQuery.extend({
   myfunction: function(param){
       // code here
   },
});
$(element).myfunction(param);
查看更多
人间绝色
3楼-- · 2019-01-01 12:38

You can also use extend (the way you create jQuery plugins):

$.fn.extend(
{
    myfunction: function () 
    {
    },

    myfunction2: function () 
    {
    }
});

Usage:

$('#my_div').myfunction();
查看更多
只若初见
4楼-- · 2019-01-01 12:41
$(function () {
    //declare function 
    $.fn.myfunction = function () {
        return true;
    };
});

$(document).ready(function () {
    //call function
    $("#my_div").myfunction();
});
查看更多
低头抚发
5楼-- · 2019-01-01 12:41

It sounds like you want to extend the jQuery object via it's prototype (aka write a jQuery plugin). This would mean that every new object created through calling the jQuery function ($(selector/DOM element)) would have this method.

Here is a very simple example:

$.fn.myFunction = function () {
    alert('it works');
};

Demo

查看更多
旧时光的记忆
6楼-- · 2019-01-01 12:46

Simplest example to making any function in jQuery is

jQuery.fn.extend({
    exists: function() { return this.length }
});

if($(selector).exists()){/*do something here*/}
查看更多
零度萤火
7楼-- · 2019-01-01 12:50

Create a "colorize" method:

$.fn.colorize = function custom_colorize(some_color) {
    this.css('color', some_color);
    return this;
}

Use it:

$('#my_div').colorize('green');

This simple-ish example combines the best of How to Create a Basic Plugin in the jQuery docs, and answers from @Candide, @Michael.

查看更多
登录 后发表回答