繁体   English   中英

jQuery元素CLICK函数IF(对于每个css_attribute =值)然后更改css值

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

我是一个jQuery NEWB,试图弄清楚为什么它不起作用。 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>

脚本:

$(".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)'});
        }
    });
});

实际的整体问题要复杂得多,这不是实际的代码,但是根据我在此处可以找到的解决方案,这是等效的。

在您的情况下,将您的js部分更改为以下内容。 那么它将解决问题。

 $(".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)'}); } }); }); 

否则这就是您可以做到的。 请参考工作示例和示例代码。 希望这对您有帮助。

 <!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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM