当前位置: 动力学知识库 > 问答 > 编程问答 >

How to use $(this) inside a 'sub function' in jQuery?

问题描述:

This function call

$('#mydiv').paintRed();

paints the background of the DOM element with id mydiv red, if you're using this code:

$.fn.paintRed = function() {

$(this).css("background-color", "red");

}

Well, okay. But now I want to 'group' my own functions. Now I want the programmer to use this function call to achieve the same as above:

$('#mydiv').subsub.paintRed();

How do I achieve that?

(Or else, if above request is not possible, is there any other way?)

网友答案:
    $.fn.subsub= function() {
       var that = this;
        return {
            "paintRed" : function(){
                $(that).css("background-color", "red");
            },
            "yourOwnFunction1" : function(){
                 //code here
             },
            "yourOwnFunction2" : function(){
                 //code here
             }
        };
    }
    $("#mydiv").subsub().paintRed();
//  $("#mydiv").subsub().yourOwnFunction1();

Return an Object that has paintRed as its property. By using this method all your functions can be "grouped" into the subsub function.

Fiddle

网友答案:

You can extend functions using jquery

$.fn.someFunctionName = function(){
// do something
}

Check the DEMO here

分享给朋友:
您可能感兴趣的文章:
随机阅读: