jQuery切换类后二次点击事件失效问题求助
问题分析与解决方案
原问题场景
点击带有show_box类的#init元素时,#box可正常显示,同时元素类切换为hide_box;但切换类后点击该元素,无法触发#box隐藏逻辑,即使DOM中类已成功变更。
原代码
JS代码
jQuery(document).ready(function() { if(jQuery("#init").hasClass("show_box")) { jQuery("#init").click(function() { jQuery("#box").show(1000); jQuery("#init").removeClass("show_box"); jQuery("#init").addClass("hide_box"); }); } }); jQuery(document).ready(function() { if(jQuery("#init").hasClass("hide_box")) { alert("ok"); jQuery("#box").hide(1000); } });
HTML代码
<div id="box" style="position:relative;width:100px;height:100px;background-color:red;display:none;"></div> <span id="init" class="show_box"> Box Action </span>
问题原因
- 第二个
document.ready中的逻辑是页面加载完成时一次性执行的,页面初始化时#init的类是show_box,这段代码直接跳过,后续类变更后不会再触发这段逻辑。 - 第一个点击事件仅在页面加载时判断
show_box才绑定,类切换后该点击事件依然存在,但没有处理hide_box状态的分支逻辑。
修正后的代码
JS代码
jQuery(document).ready(function() { // 给#init绑定单次点击事件,每次点击时实时判断当前类状态 jQuery("#init").click(function() { const $init = jQuery(this); const $box = jQuery("#box"); if ($init.hasClass("show_box")) { $box.show(1000); $init.removeClass("show_box").addClass("hide_box"); } else if ($init.hasClass("hide_box")) { $box.hide(1000); $init.removeClass("hide_box").addClass("show_box"); } }); });
HTML代码(无需修改)
<div id="box" style="position:relative;width:100px;height:100px;background-color:red;display:none;"></div> <span id="init" class="show_box"> Box Action </span>
逻辑说明
- 只绑定一次点击事件,每次点击时实时检查当前元素的类状态,避免页面初始化时的静态判断限制。
- 显示/隐藏操作完成后,同步切换类,确保下次点击时能触发对应逻辑。
内容的提问来源于stack exchange,提问作者Jean
相关产品推荐
相关产品推荐

