简体   繁体   中英

How can I change background color with jQuery?

I have an array that looks like this:

tracker[0] = false
tracker[1] = true
tracker[2] = true
tracker[3] = false

and some Div's on my form that look like this:

<div id="tracker_0"> </div>
<div id="tracker_1"> </div>
<div id="tracker_2"> </div>
<div id="tracker_3"> </div>

What I need is to change the background color of my Div's to red or green depending on the value of my tracker array. This is an array that's a variable size.

Can someone give me some pointers how I could do this using jQuery. I really have little experience with this so I would very much appreciate any help.

thank you, Marilou

Without some code, it's impossible to write working code, but can be something like this:

function (){
    var i = 0;
    $("#divWrapper div").each(function(){
        if(tracker[i])
            $(this).css("background-color","red");
        else
            $(this).css("background-color","green");
        i++;
    });
}

Where this function is a parameter of your trigger

Edit:

Now that you provided the code, try this:

for(i=0; i<tracker.length; i++)
{
    if(tracker[i])
        $("#tracker_"+i).css("background-color","green");
    else
        $("#tracker_"+i).css("background-color","red");
}
$.each(tracker, function (i, bool) {
    $('#tracker_'+i).css('backgroundColor', bool ? 'green' : 'red');
});

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