简体   繁体   中英

Calling user-defined function on jQuery object

I want the color of the text to change when I click it. This is the code I'm using right now:

$(document).ready(function() {
    $("#colorChanger p").click(function() {
        $(this).changeColor();
    });

    function changeColor() {
        $(this).css("color", "white");
    };
})

I also have this code on JSFiddle . What's wrong with my code?

Updated the fiddle: http://jsfiddle.net/xME2L/5/

If you wish to add a function so you can call it on whatever is returned from $(), you must use:

$.fn.functionName = function() {}

Here is my solution . You were not passing the object correctly to the changeColor function. I would also recommend declaring changeColor outside of the document.ready function.

The changecolor function was never assigned to the jquery el object.

An alternative to agmcleod 's solution would be :

$(document).ready(function(){

        $("#colorChanger p").click(function(){
           changeColor($(this));
         });

        function changeColor(el){
            el.css("color","white");
        };
});

http://jsfiddle.net/dq6yv/

As an alternative to agmcleod's solution , you could call changeColor this way (without changing changeColor ):

changeColor.call(this);

Demo the change here .

You should define changeColor as a JQuery plugin if you want to call it like $(this).changeColor(); :

$(document).ready(function(){            
    $("#colorChanger p").click(function(){
        $(this).changeColor();
    });

    $.fn.changeColor = function() {
      this.css("color","white");
    };

})

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