修改Iframe内select选项文本时change事件多次触发后失效咨询
问题根因
你当前代码的change事件直接绑定在iframe内首次渲染的select元素上,Shopify Buy组件的iframe DOM会在用户每次选择选项后触发重绘,原有绑定了事件的select元素会被销毁替换为新节点,旧的事件绑定随之失效,就会出现几次操作后逻辑不触发的问题。
修复方案
改用事件委托机制,把事件绑定在iframe内不会被重绘的顶层document对象上,不管内部select重建多少次都能捕获到change事件,仅需改动一行绑定逻辑即可修复:
//when page loads setTimeout(function() { var iframePreLoad = $("#product-component-1635439141053").children().contents(); iframePreLoad.find(".shopify-buy__option-select__select").ready(function(){ iframePreLoad.find('select[name=Color] option:nth-child(1)').html('Black'); iframePreLoad.find('select[name=Color] option:nth-child(2)').html('Green'); }); //When selection is made // 核心改动:把事件绑定到iframe文档对象,用委托方式匹配select元素 iframePreLoad.on('change', 'select', function() { setTimeout(function() { iframePreLoad.find('select[name=Color] option:nth-child(1)').html('Black'); iframePreLoad.find('select[name=Color] option:nth-child(2)').html('Green'); },100) console.log('selection changed'); }); }, 3000);
如果想要更稳定的执行效果,也可以把硬编码的3秒延时替换为iframe加载完成的监听事件,避免网络慢的时候iframe还没加载完成就执行逻辑:
// 监听iframe加载完成后再执行逻辑,兼容性更好 $('#product-component-1635439141053 iframe').on('load', function() { const iframeDoc = $(this).contents(); // 页面加载时替换选项文本 iframeDoc.find('select[name=Color] option:nth-child(1)').html('Black'); iframeDoc.find('select[name=Color] option:nth-child(2)').html('Green'); // 事件委托绑定change事件 iframeDoc.on('change', 'select', function() { setTimeout(() => { iframeDoc.find('select[name=Color] option:nth-child(1)').html('Black'); iframeDoc.find('select[name=Color] option:nth-child(2)').html('Green'); }, 100); console.log('selection changed'); }); });
内容的提问来源于stack exchange,提问作者Vim Bonsu
相关产品推荐
相关产品推荐

