jQuery 为委托输入字段设置值

jQuery set value to delegated input fields

我有如下 HTML 代码。

<table id="items">
 <tr class="item-row">
        <td class="item-name"><div class="delete-wpr"><a class="delete" href="javascript:;" title="Remove row">-</a></div></td>
        <td><input type="text" id="slslno" class="slno"/></td>
        <td><input type="text" class="cost"/></td>
        <td><input type="text" class="qty"/></td>
        <!--  <td><span class="price"></span></td>-->
        <td class="price"></td>
        <a class="add" id="addrow" href="javascript:;" title="Add a row">+</a> </tr>

</table>

它有一个名为 "Add a row" 的按钮,可以动态添加更多行。

然后我有这个绑定,它在 slno 字段模糊期间调用更新函数。

  function bind()
  {
      $(".slno").blur(update_unitcost);
  }

函数update_unitcost如下

function update_unitcost()    
{
    var unitprice1=$(this).val();
    unitprice={"unitpricereal":unitprice1};
    $.ajax({
        type: "POST",
        url: "findcost.php",
        data: unitprice,        

        success: function(unitp){           
            $( ".cost" ).val(unitp);        
        }
    });                
}

在上面的函数中,我可以使用 this 选择器获取值,但是当涉及到在下一行中设置值时,

$( ".cost" ).val(unitp);

它只是将每个“.cost”类 重置为该特定数字。如何为各个委托行设置值?我也尝试了下面的方法,但是失败了。

 var row = $(this).parents('.item-row');
 row.find('.cost').val(unitp);

在您的函数中设置一个变量,以仅针对您希望更新的特定 .cost 元素,而不是所有元素。

function update_unitcost()    
{
    var unitprice1=$(this).val();
    var costItem = $(this).parent().parent().find('td input.cost');
    unitprice={"unitpricereal":unitprice1};
    $.ajax({
      type: "POST",
      url: "findcost.php",
      data: unitprice,        

      success: function(unitp){           
       costItem.val(unitp);        
      }
    });                
}