[英]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.