我有一个JavaScript函数drawGrid(),它可以创建表,行和单元格。
如果我在函数内部添加appendChild(table),一切都很好,该表将被显示。
但是我想返回表并在调用drawGrid()的函数中进行追加
这是drawGrid()的结尾:
console.log(table instanceof HTMLElement) // true
console.log(table instanceof Node) // true
return table;
我在哪里调用drawGrid():
var table = new Grid()....
console.log(table instanceof HTMLElement) // false
console.log(table instanceof Node) // false
......appendChild(table);
未捕获的TypeError:无法在“节点”上执行“ appendChild”:参数1的类型不是“节点”。
我如何返回表,以便它仍然记得它是Node和HTMLElement的实例,所以我可以追加child(table)吗?
在整个代码下面:
function Grid(rows, cols, cellSize, line, thicker, xDivision, yDivision, gridColor, topMargin, opacity) {
Shape.apply(this, arguments);
this.rows = rows;
this.cols = cols;
this.cellSize = cellSize;
this.line = line;
this.thicker = thicker;
this.xDivision = xDivision;
this.xAccent = rows/xDivision;
this.yDivision = yDivision;
this.yAccent = cols/yDivision;
this.topMargin = topMargin;
this.opacity = opacity;
this.gridColor = gridColor;
this.drawGrid(this.rows, this.cols, this.cellSize, this.line, this.thicker, this.xAccent, this.yAccent, this.gridColor, this.topMargin, this.opacity);
};
Grid.prototype = Object.create(Shape.prototype);
Grid.prototype.constructor = Grid;
Grid.prototype = {
drawGrid: function(rows, cols, cellSize, line, thicker, xAccent, yAccent, gridColor, topMargin, opacity) {
var table = document.createElement("TABLE");
table.setAttribute("id", "hundred_square");
table.style.cssText +=';'+ "width: "+ (cols*cellSize) +"vw; height: "+ (rows*cellSize) +"vw; border-collapse: collapse; border: "+ (5*line) +"vw solid" +gridColor+ "; margin: " +topMargin+ "vw auto;";
for(var i=0; i < rows; i++){
var row = document.createElement("TR");
table.appendChild(row);
row.style.cssText += ';' + "opacity: "+ opacity +"; filter: alpha(opacity="+ (opacity*100) +");";
for(var j=0; j < cols; j++){
var cell = document.createElement("TD");
row.appendChild(cell);
cell.style.cssText += ';' + "width: "+ cellSize +"vw; height: "+ cellSize +"vw; border-right: "+ (j%yAccent==(yAccent-1) ? thicker*line : line) +"vw solid " +gridColor+ "; border-bottom: "+ (i%xAccent==(xAccent-1) ? thicker*line : line) +"vw solid " +gridColor+ ";opacity: 0."+ opacity +"; filter: alpha(opacity="+ (opacity*100) +");";
}
}
//document.getElementById("js_animation").appendChild(table);
console.log(table instanceof HTMLElement) //true
console.log(table instanceof Node) //true
return table;
}
};
还有其他地方:
var table = new sl.Shapes.Grid(10, 10, 3.5, 0.1, 5, 2, 2, "#bfbf8c", 4.5, 0.85);
console.log(table instanceof sl.Shapes.Grid) // true
console.log(table instanceof HTMLElement) // false
console.log(table instanceof Node) // false
document.getElementById("js_animation").appendChild(table);
错误
最佳答案
看起来table
是Grid
,而不是HTML表本身,应该使用(new Grid()).drawGrid()
来获取表,然后可以将其附加到HTML元素。