You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery克隆行后AJAX提交重复原始值问题排查求助

问题排查与解决方案

核心问题1:全局选择器导致所有行复用同一值

你在收集每行数据时,使用$('.finition').val()这类全局选择器,它会直接选取页面中第一个匹配.finition的元素值,而非当前循环行内的输入框内容。所以不管克隆行输入什么,最终都会用第一行的数值填充。

核心问题2:克隆行ID设置不合法

var newId = '#duplicable'+index;给ID添加了#符号,导致生成的行ID为#duplicable1,不符合HTML ID规范(ID不能包含#),后续DOM操作会受影响。


修正后的完整代码

// 添加行函数
$(document).on('click', '#add_row', function(e){
  $('#del_row').prop('disabled',false)
  var index = $('.duplicable').length
  // 去掉ID里的#,生成合法ID
  var newId = 'duplicable'+index;
  var row = $('#duplicable').clone().attr("id",newId).find(':input').prop('value', '').end();
  $('#Attributes_table tbody').append(row);
});

// AJAX提交函数
$(document).on('click', '#product-submit', function(e){
  var attrs = [];
  $('.duplicable').map(function(){ 
    // 用$(this).find()限定在当前行内查找输入框
    var $currentRow = $(this);
    attrs.push({
         'id' : $currentRow.attr('id'),
        "finition": $currentRow.find('.finition').val(),
        "size": $currentRow.find('.size').val(),
        "price": $currentRow.find('.price').val(),
        "img": $currentRow.find('.img').val(),
    })
  }).get();
  $.ajax({
    type: 'POST',
    url :  window.location.pathname,
    data : {
      'ajax_post' : 'create_product',
      'designation': $('#id_designation_input').val(),
      'description': $('.editor-content').text(),
      'selected_ttag': $('#id_product_select_ttag').val(),
      'selected_ctag': $('#id_product_select_ctag').val(),
      'selected_otag': $('#id_product_select_otag').val(),
      'attr': JSON.stringify(attrs)
        
      },
    success : function(){
      console.log(attrs)
      
    },
    error: function(xhr, errmsg, err){
      console.log(xhr.status + ":"+ errmsg+ err)
    }

  });
});

验证说明

  • 修正后,每行数据通过$currentRow.find()精准获取当前行内的输入值,不会再复用第一行内容。
  • 克隆行ID变为duplicable1、duplicable2这类合法值,避免后续DOM操作出错。

内容的提问来源于stack exchange,提问作者Gabriel Tournier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:40:40