簡體   English   中英

如何使用jQuery更改我的兩個td的背景顏色?

[英]how to change background color of my two td's using jQuery?

這是我的html代碼..在以下代碼中,我有兩個具有相同背景色的td。因此,當我單擊兩個td中的任何一個時,必須使用jquery更改背景色。可以這樣做嗎?

<table id='main_table' style='width:1002px; border: 1px solid #ccc;'>
    <thead>
      <tr class='ab'>
             <td style='width:500px; background-color:#398bb7; color:white;' onclick=\"Consituteshow('"+cityid+"');\">By Constituency</td>
              <td  style='width:500px; background-color:#398bb7; color:white;' onclick=\"Partyshow('"+cityid+"');\">By Party</td>
      </tr>
    </thead>
</table>
$("td").click(function(){
  $(this).css("background", "green");
});

使用這個關鍵字

$('#main_table tr.ab td').click(function () {
    $(this).css('background-color', '#398bb7');
});

如果要更改兩個td的背景色

$('#main_table tr.ab td').click(function () {
    $(this).siblings().add(this).css('background-color', '#398bb7');
});

$('#main_table tr.ab td').click(function () {
    $(this).parent().find('td').css('background-color', '#398bb7');
});

OP發表評論后更新

使用.on()

由於元素是動態添加的,因此在DOM准備就緒或頁面加載時不存在。

所以你必須使用事件委托

句法

$( elements ).on( events, selector, data, handler );

js

$(function () {
    $(document).on('click', '#main_table td', function () {
        $("#main_table tr td").css("background-color", "#398bb7");
        $(this).css("background-color", "#FF00FF"); //Add your color
    });
});


更好地使用課堂

.active {
    background-color:green;
}

的CSS

 .active { background-color:green; } 

$(“#main_table .ab td”)。css({“ background-color”:“#f1f1f1”});

在點擊事件中添加此事件

表格背景的所有td都會改變

嘗試這個

$("#main_table tr td").click(function() {
   $("#main_table tr td").css("background-color","#398bb7");
   $(this).css("background-color","#FF00FF"); //Add your color
});

演示版

嘗試:

$(document).on("click","td",function(){
    $(this).css("background-color","red");
});

嘗試這個

  $("td").click(function() {
       $(this).css("background-color","#000");
    });
$('td').click(function()
              {
                  $(this).css('background-color','#ff0');
              }
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM