[英]HTML/CSS/JavaScript: How to change color of table row based on data
[英]Change row table color with JavaScript
我嘗試使用JavaScript更改表格中行的背景,但無法正常工作。 這是我的代碼 。 但是我試圖用html及其工作創建一個表。 PS:我想使用webkit。
代碼:
var table = document.getElementById("tab");
var rowCount = table.rows.length;
for(var i=0;i<6;i++) {
row = table.insertRow(rowCount);
row.id = "row"+i;
cell1 = row.insertCell(0);
var content = document.createElement("output");
content.innerHTML = i ;
cell1.appendChild(content);
rowCount++;
}
$(document).ready(function(){
$('td').each(function(i) {
$('#tab').on('click', '#row'+i, function(){
document.getElementById("row"+i).style.background = 'white';
//alert(i);
});
});
//example2
$('#td1').on('click', function(){
document.getElementById("td1").style.background = 'white';
});
});
您遇到的問題是因為要在TD
上設置背景漸變,然后再設置TR
的背景顏色。 由於TD在TR內,因此您只是看不到您所做的更改。
您不應該在循環中分配事件處理程序,尤其是在您不需要:
$('#tab').on('click', 'tr', function () {
$('td,th', this).css('background', 'white');
});
擺弄 。
它是backgroundColor,不是background。
第一個問題是關閉問題 。
Click事件將始終指向i的最后一個實例。
將您的代碼更改為此
$('td').each(function(i) {
(function(num) {
$('#tab').on('click', '#row' + num, function() {
document.getElementById("row" + num).style.background = '';
//alert(i);
});
})(i)
});
這可能不是非功能代碼的主要原因。
您要更改整行或當前單元格的顏色嗎? 您當前的選擇器僅適用於特定的單元格。
// for the complete row
$(document).ready(function(){
$('td').on('click',function(){
$(this).closest('tr').find('td').css({'background':'red'});
});
});
// or for the active cell..
$(document).ready(function(){
$('td').on('click',function(){
$(this).css({'background':'red'});
});
});
有關行解決方案,請參見此小提琴http://jsfiddle.net/axelmichel/2KUCz/ 。 如果您希望每個表具有不同的行為,則可以在以下位置修改選擇器:
$('#tab').find.('td').on('click',...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.