JavaScript点击按钮生成图片报错且无法切换图片问题求解
错误原因&修复方案
1. 语法错误修复
你遇到的Uncaught SyntaxError是因为直接写1024px没有加引号,JS会将px识别为未定义的变量触发语法报错。img.width/img.height支持两种赋值方式:
- 直接赋值数值,默认单位为px:
img.width = 1024 - 赋值带单位的字符串:
img.width = "1024px"
2. 其他逻辑问题修复
你的代码还存在两处逻辑问题导致功能无法运行:
- 仅在点击回调中定义了
show_image函数,没有主动调用,点击按钮不会触发图片创建 - 没有旧图片清理逻辑,不符合每次仅展示一张图片的需求
完整修复后代码
<script> // 给动态生成的图片设置统一标识,方便查找删除 const DYNAMIC_IMG_ID = "dynamic-show-img"; var RestyledButton = document.querySelector('#RestyledButton'); RestyledButton.onclick = function () { showImage("https://badzingerauto.com/wp-content/uploads/2021/08/0-02-0a-9f28adad47f010eda8970ef447fc0a0c48bc08b66d6f61dd5ac3c17ea3602f75_157750a049205ef1-1024x768.jpg"); }; var UnrestyledButton = document.querySelector('#UnrestyledButton'); UnrestyledButton.onclick = function () { showImage("https://badzingerauto.com/wp-content/uploads/2021/08/0-02-0a-cf2e0f59f9ecbadf6b08b1108448506868d680ca23b181b5d7891493d575962d_ee21b4da7f002dbb-1024x768.jpg"); }; // 抽离公共的图片创建逻辑 function showImage(src) { // 先删除已存在的动态图片 const existImg = document.getElementById(DYNAMIC_IMG_ID); if(existImg) existImg.remove(); // 创建新图片 const img = document.createElement("img"); img.id = DYNAMIC_IMG_ID; img.src = src; img.width = 1024; img.height = 768; document.body.appendChild(img); } </script>
内容的提问来源于stack exchange,提问作者Regular User
相关产品推荐
相关产品推荐

