我具有此功能,应该将所有TD的背景色存储在表中。一些TD将没有指定的背景色。那些不要跳过的人,不得存储它们。但是,我无法实现此目的,我在Firefox控制台中遇到了此错误:
TypeError: $(...).css(...) is undefined
在下面的代码中,您会发现我正在尝试跳过没有背景色属性的TD。但是无论如何,该程序都会继续前进,并且无论如何都会返回此错误。
var canvasString = '';
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var attr = $('#' + x + '-' + y).attr('background-color');
if (attr !== 'undefined') {
if ($('#' + x + '-' + y).css('background-color') !== 'transparent' && $('#' + x + '-' + y).css('background-color') !== null && $('#' + x + '-' + y).css('background-color') !== 'undefined') {
canvasString = canvasString + x + ' ' + y + ' ' + ($('#' + x + "-" + y).css('background-color')).replace(/s/g, '') + "n";
}
}
}
}
document.getElementById('canvas').value = canvasString;
我在做什么错?
首先,if (x !== 'undefined')
不会测试该变量是否未定义;它测试变量是否等于 string , 'undefined'
。测试变量是否不确定
if (typeof x !== 'undefined') ...
但是,您的代码还有其他问题。目前尚不清楚您在这里要做什么,但请尝试以下操作:
var ele = $('#' + x + '-' + y);
if (ele.length) {
canvasString += x + ' ' + y + ' ' + ele.css('background-color').replace(/s/g, '') + "n";
}
您对未定义的检查是错误的。当值不确定时,它不等于字符串"undefined"
。值的类型等于字符串:
if (typeof attr !== 'undefined') {
如果您想要一个更本地的jQuery解决方案,则可以做这样的事情:
function getBackgroundColors(colNo) {
var row = 1;
return $('table td').map(function (i, el) {
var color = $(el).css('backgroundColor');
if (color !== 'transparent') {
obj = {row: row, col: i % colNo + 1, color: color};
}
if (i % colNo === 1) row++;
return obj;
});
}
console.log(getBackgroundColors(2));
这将为您提供一系列指定行,列和颜色的单元对象,例如:
[Object { row=1, col=1, color="rgb(239, 239, 239)"}, Object { row=1, col=2, color="rgb(239, 239, 175)"}, Object { row=2, col=1, color="rgb(239, 239, 175)"}, Object { row=2, col=2, color="rgb(239, 63, 239)"}