简体   繁体   中英

How to pass object from jquery to javascript

I wanna pass an object from jquery using a selector to a javascript function like below.

flash($("#something span"), "#fff", 250);

but it does not seem to be working.

and I am not sure what to put in the javascript function. What I make now is:

function flash(obj,color1,color2,duration) {
    obj.animate({backgroundColor:color1},duration);
    setTimeout(function(){this.animate({backgroundColor:color2},duration);},duration);
}

or is there another way instead of passing an object? for example, in jquery: $("this").flash("#f79999", "#eee", 250);

but then how to define the javascript function?

You have a simple syntax error.

ojb.animate({backgroundColor:color},duration);

Should be

obj.animate({backgroundColor:color},duration);

You'll have to include the jQuery.Color plugin to animate properties like background-color .

From " Animation Properties and Values :"

All animated properties should be animated to a single numeric value , except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width , height , or left can be animated but background-color cannot be, unless the jQuery.Color() plugin is used ). [...]


is there another way instead of passing an object? for example, in jquery: $("this").flash("#fff",250);

jQuery's Plugins/Authoring should help with this. But, you could define it as:

jQuery.fn.flash = function (color, duration) {
    return this.animate({ backgroundColor: color }, duration);
};

$('#something span').flash('#fff', 250);

With the jQuery.Color plugin installed in the page (ack. @Jonathan Lonowski) ...

You can avoid passing an object by using javascript's .call() or .apply() .

Here's an example :

$(function() {
    function flash(color, duration) {
        this.animate({backgroundColor:color}, duration);
    }
    $("#something span").on('click', function() {
        flash.call($(this), "#fff", 250);
    });
    $("#something_else span").on('click', function() {
        flash.apply($(this), ["#fff", 250]);
    });
});

.call() and .apply() aren't really necessary here; regular function calls would suffice.

.call() and .apply() are normally used in cases where you need to call a method of one object but give it the context of another object. By doing so, the method is made to operate on a different this .

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