JavaScript点击添加active类函数首次点击不生效问题求解
问题原因
你将active类切换的点击事件绑定逻辑,写在了点击才会触发的howAppWorks函数内部,会引发两个问题:
- 第一次点击触发
howAppWorks时,才会给所有按钮绑定点击监听,本次点击不会触发刚绑定的监听逻辑,所以首次点击不会添加active类 - 每次点击都会重复给按钮绑定监听事件,后续点击会多次执行切换逻辑,会出现冗余执行甚至异常
解决办法
直接移除嵌套的点击事件绑定逻辑,在howAppWorks内部直接处理active类的切换即可,修改后的代码如下:
JS代码
function howAppWorks($imgUrl, $myClass, event) { document.getElementById('myImage').src = $imgUrl; document.getElementById("howTheAppContent").classList.remove('addEvent', 'fillTheForm', 'rrtFlowSheet'); document.getElementById("howTheAppContent").classList.add($myClass); // 直接处理active类切换,不需要额外绑定监听 const currentActive = document.querySelector('#appWorksList .custom-class.active'); if (currentActive) { currentActive.classList.remove('active'); } // 给当前点击的元素添加active类 event.currentTarget.classList.add('active'); }
HTML调整
需要在onclick调用时传入event参数,修改后的对应片段如下:
<tr class='custom-class active' id="addEvent" onclick="howAppWorks('http:\/\/localhost/projects/rrs-website/wp-content/uploads/2021/11/how-the-app-works.png', 'addEvent', event)"> <td>1</td> </tr> <tr class='custom-class' onclick="howAppWorks('http:\/\/localhost/projects/rrs-website/wp-content/uploads/2021/11/fill-the-forms.png', 'fillTheForm', event)"> <td>2</td> </tr> <tr class='custom-class' onclick="howAppWorks('http:\/\/localhost/projects/rrs-website/wp-content/uploads/2021/11/rrt-flow-sheet.png', 'rrtFlowSheet', event)"> <td>3</td> </tr>
内容的提问来源于stack exchange,提问作者Atif Azad
相关产品推荐
相关产品推荐

