JQuery元素点击函数IF(对于每个css_attribute = value)然后改变css值

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

本文关键字:css attribute value 改变 然后 于每个 元素 函数 IF JQuery      更新时间:2023-09-26

我是一个JQuery新手,试图弄清楚为什么这不起作用。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>