jQuery 将值设置为委派的输入字段

jQuery set value to delegated input fields

本文关键字:输入 字段 委派 设置 jQuery      更新时间:2023-09-26

我有如下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>

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

然后我有这个绑定,它在 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);        
      }
    });                
}