0

我有一个代码。

var countRow = $('table#receiving-stock-view tr').length - 1;
var ar = new Array();
for(var iter=0;iter<countRow;iter++){
ar[iter] = $('div.modal table#receiving-stock-view tr#'+iter).find('input[name=rspid]').attr('id')
        +","+$('div.modal table#receiving-stock-view tr#'+iter).find('input[name=rsqty]').val()
        +","+$('div.modal table#receiving-stock-view tr#'+iter).find('input[name=rscost]').val()
        +","+$('div.modal table#receiving-stock-view tr#'+iter).find('input[name=rssrp]').val();
        console.log($('table#receiving-stock-view tr#'+iter).find('input[name=rsqty]').val());
        console.log(ar[iter]);
}

但是,在循环期间,它始终只适用于第一行。它在其他行上随机失败。

然而,

for(var iter=0;iter<countRow;iter++){
ar[iter] = $('#receiving-stock-view tr#'+iter).find('input[name=rspid]').attr('id')
        +","+$('#receiving-stock-view tr#'+iter).find('input[name=rsqty]').val()
        +","+$('#receiving-stock-view tr#'+iter).find('input[name=rscost]').val()
        +","+$('#receiving-stock-view tr#'+iter).find('input[name=rssrp]').val();
}

如果我没有指定要查找和保留 id 的元素,它会正确读取所有值。知道为什么会这样吗?这真的很奇怪。

编辑:我使用 ajax 添加了一个新行。整个表格都在一个模态类中。

<table id="receiving-stock-view">

 <thead hidden="true" style="display: table-header-group;">
 <tr>
 <th>Product</th>
 <th>Quantity</th>
 <th>Cost</th>
 <th>SRP</th>
 <th>Sub-Total</th></tr>
 </thead>

  <tbody>
 <tr id="0">
 <td><span><input type="text" value="HeadPhoneszs" name="rspid" id="1"></span></td>
 <td><input type="text" value="1" name="rsqty" id="rsqty_id"></td>
 <td><input type="text" value="1" name="rscost" id="rscost_id"></td>
 <td><input type="text" value="1" name="rssrp" id="rssrp_id"></td></tr>
 <tr id="1"><td><span><input type="text" value="vp" name="rspid" id="13"></span></td>
 <td><input type="text" value="2" name="rsqty" id="rsqty_id"></td>
 <td><input type="text" value="2" name="rscost" id="rscost_id"></td>
 <td><input type="text" value="2" name="rssrp" id="rssrp_id"></td>
 </tr>
 </tbody>
</table>
4

1 回答 1

0
  1. 当你使用

    $('div.modal table#receiving-stock-view tr#'+iter)
    

浏览器首先查找具有modal类的 div。根据您的评论,您确实有超过 1 个具有同一类的 div。这可以使浏览器选择任何一个 div 元素。所以这可能会随机失败。

  1. 当你使用

    $('#receiving-stock-view tr#'+iter)
    

浏览器尝试将receiving-stock-view表的 id 与 DOM 元素匹配。由于其独特性,它每次都能成功匹配表行。

如果您能够使用id进行匹配,那么这是在 DOM 中匹配元素的最佳和最有效的方式。在这种情况下,不需要预选器,它们会降低网页的性能。

于 2016-12-15T09:10:54.443 回答