簡體   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