克隆表单行后select的data-row取值异常,无法更新对应输入框
问题
表单中带data-size属性的select选项,change事件触发时能正常把选中的data-size值填充到相邻输入框。但添加克隆表单行的+按钮后,克隆行的select选择选项时,通过var row = $(this).data("row");获取的值始终是初始行的1,导致每次都更新第一行的输入框,而非当前行的。
问题原因
jQuery的.data()方法会将首次读取的data-*属性值缓存到元素的内存中,后续调用.data('row')时优先读取缓存值,而非DOM上的data-row属性。克隆行时你只修改了DOM的data-row属性,但没有更新jQuery缓存的data值,所以克隆后的select调用.data('row')时,还是读取初始行缓存的1。
解决方案
方案1:直接读取DOM属性值
不用.data(),改用.attr('data-row')读取DOM上的data-row属性,这样每次都会获取最新的属性值:
$('#myform') .on('change', '.getclothsize', function(e) { var size = $(this).find('option:selected').data("size"); // 改用attr读取属性 var row = $(this).attr("data-row"); console.log("size " + size + " from row = " + row); if (size != null) { $("input[name='size-" + row + "']").val(size); } });
方案2:更新jQuery缓存的data值
在克隆修改data-row属性后,用.data('row', counter)同步更新缓存值:
var $template = $('.copy-row').slice(-1).clone(true, true).find('input').end() .find('.addInput').removeClass('addInput').addClass('removeInput').text('-').end() .find('[name^="cloth-"]').attr('name', 'cloth-' + counter).attr('tabindex', counter).val(null) .attr('data-row', counter) // 新增这行更新缓存的data值 .data('row', counter) .end() .find('[name^="size-"]').attr('name', 'size-' + counter).attr('tabindex', counter).val("").end()
优化方案:通过DOM关系定位输入框
完全摆脱对data-row和name属性的依赖,直接通过DOM层级关系定位当前行的输入框,更健壮且简洁:
$('#myform') .on('change', '.getclothsize', function(e) { var size = $(this).find('option:selected').data("size"); // 直接通过父元素找当前行的输入框 var $input = $(this).closest('.copy-row').find('[name^="size-"]'); if (size != null) { $input.val(size); } });
内容的提问来源于stack exchange,提问作者yaylitzis
相关产品推荐
相关产品推荐

