JavaScript Toggle Image控件图片无法显示,求修复方案
修复你的Toggle Image控件问题
我帮你找出了代码里的几处关键问题,修复后就能正常切换图片了:
问题分析
- 类名拼写错误:
ToogleImage应该改为ToggleImage(少了字母g,虽然不影响运行,但符合规范) - toggleState方法逻辑错误:原代码里的
this.toggled!=this.toggled();是错误写法,正确的状态反转应该是this.toggled = !this.toggled; - refreshImage方法未绑定实例属性:直接使用
img会引用全局变量,应该用this.img访问类实例中的图片元素 - 点击事件的this指向问题:普通
function回调里的this指向的是触发点击的<img>元素,不是你的ToggleImage实例,需要改用箭头函数来保留正确的上下文
修复后的完整代码
<html> <head> </head> <body> <div id="box"> </div> </body> <script> class ToggleImage{ constructor(imgToggled, imgNotToggled, img){ this.toggled = false; this.imgToggled = imgToggled; this.imgNotToggled = imgNotToggled; this.img = img; this.refreshImage(); // 改用箭头函数保留this指向类实例 this.img.addEventListener('click', (e) => { this.toggleState(); this.refreshImage(); }); } toggleState(){ // 正确反转状态 this.toggled = !this.toggled; } refreshImage(){ // 使用this.img访问实例的图片元素 if(this.toggled){ this.img.setAttribute('src', this.imgToggled); }else{ this.img.setAttribute('src', this.imgNotToggled); } } } var img = document.createElement("img"); // 修正类名 var toggleImage = new ToggleImage("https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded", "https://www.stackoverflowbusiness.com/hubfs/B2B-SO/images/SO_Talent.svg?t=1515694040462", img); document.getElementById('box').appendChild(img) </script> </html>
额外优化建议
- 可以给图片添加基础样式(比如固定宽高),让切换效果更明显
- 可以在构造函数里给图片加上
alt属性,提升可访问性
内容的提问来源于stack exchange,提问作者Curunir
相关产品推荐
相关产品推荐

