jQuery if else语句无法随元素current类变更自动生效问题求助
问题原因
你的脚本仅在页面加载、脚本首次执行时运行一次判断逻辑,没有设置任何触发机制监听current类的变更事件,因此类名变化后不会重新执行显示/隐藏按钮的逻辑,自然不会同步更新状态。
解决方案
方案1:关联类名变更逻辑(推荐)
首先将你的判断逻辑封装为可复用的函数,找到页面中负责修改handling-inner元素current类的原有代码,在每次修改完current类后主动调用这个函数即可。
示例代码:
// 封装逻辑为独立函数 function updateButtonState() { const $yesBtn = jQuery(".chbs-booking-extra-list-item-quantity-enable.first .chbs-button:first-child"); const $noBtn = jQuery(".chbs-booking-extra-list-item-quantity-enable.first .chbs-button:nth-child(2)"); if (jQuery(".handling-inner.one").hasClass("current")) { $yesBtn.hide(); $noBtn.show(); } else { // two和three的逻辑一致,可以合并 $yesBtn.show(); $noBtn.hide(); } } // 页面首次加载时执行一次 jQuery(document).ready(function(){ updateButtonState(); }); // 找到原有代码中修改current类的位置,比如切换选项的点击事件里,加一行调用 // 示例原有切换逻辑位置: // jQuery(".switch-option").click(function(){ // // ...原有切换current类的代码 // updateButtonState(); // 新增这行即可同步按钮状态 // })
方案2:监听类名变化(无需修改原有代码)
如果找不到修改current类的原有逻辑,或者无法修改原有代码,可以用MutationObserver API监听handling-inner元素的类名变化,一旦类名变更就自动执行更新逻辑:
// 页面加载完成后初始化监听 jQuery(document).ready(function(){ // 先执行一次初始化状态 updateButtonState(); // 选择要监听的节点 const targetNodes = document.querySelectorAll(".handling-inner"); // 配置监听项:只监听class属性的变化 const observerConfig = { attributes: true, attributeFilter: ["class"] }; // 创建观察者实例 const observer = new MutationObserver(function(mutations) { mutations.forEach(function() { // 类名变化时执行更新逻辑 updateButtonState(); }); }); // 为所有handling-inner元素绑定监听 targetNodes.forEach(function(node) { observer.observe(node, observerConfig); }); });
内容的提问来源于stack exchange,提问作者Jituu
相关产品推荐
相关产品推荐

