求助:点击像素后触发Uncaught TypeError: pixel()不是函数错误
问题排查:Uncaught TypeError: pixel() is not a function
我正在开发一个名为"nork"的项目前置网页,该网页可创建50x50像素的双色绘图板(导出功能暂未实现)。点击按钮生成绘图板后,单点击像素可将其设为白色,双击可设为黑色。但首次点击像素后,再次点击任意像素都会触发以下错误:
Uncaught TypeError: pixel() is not function at HTMLImageElement.onclick (main.html:1:1)
完整代码
<html> <head> <title>nork Image Format Converter</title> <script> var width, height; var tableDiv; var table; let i, j; function pixel(id, color) { pixel = document.getElementById(id); if (color==0) { pixel.src = "pixelBlack.png"; } if (color==1) { pixel.src = "pixelWhite.png"; } else { window.alert("Error in color argument passed to pixel() function. Not recognized color code. Avaiable colors are: 0(black), 1(white).") } } function createImageTable() { width = 50; height = 50; tableDiv = document.getElementById("image"); table = ""; for (i = 0; i<height; i++) { for (j = 0; j<width; j++) { table += "<img src=\"pixelBlack.png\" id=\"" + i.toString() + j.toString() + "\" onClick = \"pixel('" + i.toString() + j.toString() + "', 1);\" onDblClick = \"pixel('" + i.toString() + j.toString() + "', 0);\">"; console.log(i.toString(), j.toString(), i, j); } table += "<br>" } tableDiv.innerHTML = table; } </script> <head> <body> <button onClick="createImageTable()">Create image table</button> </div> <br> <div id="draw-image"> <h3>Draw image</h3> <p>To draw single-click a pixel to colour it white, to colour it black - so to erease it - double-click the pixel.</p> <div id="image"></div> </div> <body> </html>
错误原因
- 全局变量污染:在
pixel函数内部,直接写了pixel = document.getElementById(id);,没有用var/let/const声明变量,导致该语句会修改全局作用域中的pixel标识符。首次调用pixel()函数时,全局的pixel函数会被覆盖成获取到的DOM元素,后续再点击像素时,pixel已经是DOM元素而非函数,因此触发错误。 - 语法逻辑错误:原函数中
if (color==0)之后直接使用if (color==1),没有用else if,这会导致当color=0时,依然会执行第二个判断,最终触发else分支的错误提示。
修复方案
- 给函数内部的DOM元素变量添加局部声明,避免覆盖全局函数;
- 修正
if判断的逻辑结构,使用else if确保分支互斥。
修改后的pixel函数:
function pixel(id, color) { // 用let声明局部变量,避免污染全局函数 let pixelElement = document.getElementById(id); if (color === 0) { pixelElement.src = "pixelBlack.png"; } else if (color === 1) { pixelElement.src = "pixelWhite.png"; } else { window.alert("Error in color argument passed to pixel() function. Not recognized color code. Available colors are: 0(black), 1(white)."); } }
内容的提问来源于stack exchange,提问作者Alessio Spinellino
相关产品推荐
相关产品推荐

