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

如何使用jQuery向表格同一行追加td元素?现有代码异常排查

问题根源

你代码的核心错误是选择器范围错误,导致每次数据都会追加到所有行上,还有几处细节问题:

  • 选择器范围错误:$("#example > tbody > tr").append(txt) 这个选择器选中了tbody下的所有tr行,所以每次提交新数据时,所有已存在的行都会被追加新的td单元格,这是第二次提交数据同时出现在两行的直接原因。你应该只选中当前正在编辑的对应行。
  • 类名格式错误:新增行的类名多了多余空格,代码里写的是class="txt_ '+ nextindex +'",txt_后面多了空格,最终生成的类名是txt_ 1而不是预期的txt_1,后续通过类名选择行时会匹配失败。
  • 缺少lastid赋值逻辑:你代码中用到的lastid没有对应的赋值逻辑,需要补充「输入框聚焦时记录当前激活的输入框id」的逻辑,否则lastid会取不到或者值错误。
  • 请求规范问题:AJAX请求的method指定为POST,但参数却拼接在URL里做GET传参,不符合POST请求的规范,应该把参数放到data配置项里。
  • 循环内txt赋值错误:for循环内每次都直接给txt赋值而非累加,会导致多条返回数据时只保留最后一条的单元格内容。

修正后的代码

JS部分

// 全局变量存储当前激活的输入框id
let lastid = 'txt_1';
// 新增:输入框聚焦时更新lastid
$(document).on('focus', '.txtfield', function() {
  lastid = $(this).attr('id');
});

$(document).ready(function() {
  $('.zk_btn').click(function(e) {
    var pass_symbol= $('#' + lastid).val();
    var split_id = lastid.split("_");
    var currentIndex = Number(split_id[1]);
    var nextindex = currentIndex + 1;

    $.ajax({
      url:"record_count_3.php",
      method:"POST",
      data: {pass_symbol: pass_symbol},
      success:function(data) {
        var json = JSON.parse(data);
        var txt = '';

        if(json.length > 0){
          for(var i=0;i<json.length;i++){
            txt += "<td>"+json[i].openrate+"</td><td>"+json[i].highrate+"</td><td>"+json[i].lowrate+"</td><td>"+json[i].closerate+"</td>";
          }
          // 仅选中当前编辑的行追加单元格
          $("#example > tbody > tr.txt_" + currentIndex).append(txt);
          // 移除类名多余空格
          $('#example > tbody').append('<tr class="txt_'+ nextindex +'"><td><input type="text" id="txt_'+ nextindex +'" name="symbol"  class="txtfield"  /></td></tr>');
        }   
        $('.content').html(data);
      }
    })
  });
});

HTML补充修正

你原有HTML代码thead部分缺失了<tr>开头标签,补上后完整代码如下:

<table id='example' border='1' cellspacing='1' cellpadding='1' style='width:900px;' >
  <thead>
    <tr>
      <th> Marksymbol</th>
      <th class='namecol '> Openrate</th>
      <th class='namecol'> Highrate</th>
      <th class='namecol'> Lowrate</th>
      <th class='namecol'> Closerate</th>
    </tr>
  </thead>
  <tbody>
    <tr class ='txt_1'>
      <td > <input type='text' name="symbol" id='txt_1'  class='txtfield'/>
      </td>
    </tr>
  </tbody>                                        
</table>

<input type="button" id= "btnclick" class="zk_btn zk_btn_submit" name="submit1" value="SUBMIT"/> 

内容的提问来源于stack exchange,提问作者Faizan Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:00:04