简体   繁体   中英

JQuery element CLICK function IF (for each css_attribute = value) then change css value

I'm a JQuery NEWB trying to figure out why this doesn't work. HTML:

<div class="box" style="background-color:rgb(0, 0, 255);">div 0</div>
<div class="box" style="background-color:rgb(0, 0, 255);">div 1</div>
<div class="box">div 2</div>
<button>
<a class="button">
click
</a>
</button>

SCRIPT:

$(".button").click(function() { 
    $('.box').each(function(i) {
        var color = $(this).css('background-color');
        if (color == 'rgb(0, 0, 255)') {
            $("div#box").css ({'background-color':'rgb(255, 0, 0)'});
        }
    });
});

The actual over all problem is much more complex and this is NOT the actual code, but this is an equivalent based from what solutions I could find on here.

In your case change your js part to below. then it will solve the problem.

 $(".button").click(function() { $('.box').each(function(i) { var color = $(this).css('background-color'); if (color == 'rgb(0, 0, 255)') { $(this).css ({'background-color':'rgb(255, 0, 0)'}); } }); }); 

or else this is how you can do it. refer the working demo and the example code. hope this will help to your.

 <!DOCTYPE html> <html> <head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> </head> <style type="text/css"> </style> <body> <div class="holder"> <div id="0i" class="box" style="background-color:rgb(0, 0, 255);">div 0</div> <div id="1i" class="box" style="background-color:rgb(0, 0, 255);">div 1</div> <div id="2i" class="box">div 2</div> </div> <button> <a class="button"> click </a> </button> <script type="text/javascript"> $(".button").click(function() { var the_length = $("div.holder div").length; for(var i=0;i<the_length;i++) { var color_code = $("div #"+i+"i").css("background-color"); if (color_code == "rgb(0, 0, 255)") { $("div#"+i+"i").css ({'background-color':'rgb(255, 0, 0)'}); } } }); </script> </body> </html> 

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