代码之家  ›  专栏  ›  技术社区  ›  CobaltGecko

当使用HTML输入字段中的值时,Javascript会中断

  •  0
  • CobaltGecko  · 技术社区  · 4 年前

    我正在尝试创建特定高度的输入网格。如果我在下面的画布中硬编码高度和宽度(本例中为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();
    })
    

    你知道这是什么原因吗?如果我记录高度。值和宽度。值它得到的值很好,所以我很难看出,如果这些值被很好地读取,它与硬编码有什么不同? 我得到的错误是:

    帆布js:18未捕获类型错误:无法设置未定义的属性(设置“0”) 在画布上。generateCanvas(canvas.js:18:33) 在HTMLInputElement。(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();
            }
        }
    }
    
    2 回复  |  直到 4 年前
        1
  •  1
  •   Joe Lewis    4 年前

    height.value width.value 可能是字符串类型。

    试试这个:

    new Canvas(document.getElementById("canvas-window"), parseInt(height.value), parseInt(width.value));
    
        2
  •  1
  •   jkoch    4 年前

    您直接使用的是输入值,它是一个字符串。尝试使用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();
    })