我正在嘗試創建一個給定輸入的特定高度/寬度的網格。如果我在下面的畫布(在本例中為 10 和 5)中的高度和寬度進行硬編碼,它可以完美地作業
const canvasWindow = document.getElementById("canvas-window")
const height = document.getElementById("height")
const width = document.getElementById("width")
const generateCanvasBtn = document.getElementById("generate-canvas-btn")
generateCanvasBtn.addEventListener("click", () => {
const canvas = new Canvas(document.getElementById("canvas-window"), 10, 5);
canvas.generateCanvas();
})
這個例子打破了:
const canvasWindow = document.getElementById("canvas-window")
const height = document.getElementById("height")
const width = document.getElementById("width")
const generateCanvasBtn = document.getElementById("generate-canvas-btn")
generateCanvasBtn.addEventListener("click", () => {
const canvas = new Canvas(document.getElementById("canvas-window"), height.value, width.value);
canvas.generateCanvas();
})
有什么想法可能導致這種情況嗎?如果我記錄 height.value 和 width.value 它得到的值就好了,所以我很難看到如果值被很好地讀取,它與硬編碼有什么不同?我得到的錯誤是:
canvas.js:18 未捕獲型別錯誤:無法在 HTMLInputElement 的 Canvas.generateCanvas (canvas.js:18:33) 處設定未定義的屬性(設定“0”)。(pixelcreator.js:8:12)
這是包含錯誤參考的行的代碼:
class Canvas {
grid;
constructor(window, height, width) {
this.window = window;
this.height = height;
this.width = width;
}
generateCanvas() {
this.grid = new Array(this.height).fill(0).map(() => new Array(this.width).fill(0));
for (let i = 0; i < this.height; i ) {
const row = document.createElement("div");
row.classList.add('row');
this.window.appendChild(row);
for (let j = 0; j < this.width; j ) {
this.grid[i][j] = new Cell(row) // this is line 18 from the error
this.grid[i][j].createCell();
}
}
}
uj5u.com熱心網友回復:
height.value或者width.value可能是字串型別。
嘗試這個:
new Canvas(document.getElementById("canvas-window"), parseInt(height.value), parseInt(width.value));
uj5u.com熱心網友回復:
您正在直接使用輸入的值,它是一個字串。嘗試使用 parseInt(...) 將其決議為整數
const canvasWindow = document.getElementById("canvas-window")
const height = document.getElementById("height")
const width = document.getElementById("width")
const generateCanvasBtn = document.getElementById("generate-canvas-btn")
generateCanvasBtn.addEventListener("click", () => {
const canvas = new Canvas(document.getElementById("canvas-window"), parseInt(height.value), parseInt(width.value));
canvas.generateCanvas();
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/443844.html
標籤:javascript html
