在jquery中添加带有.bfore的输入时的小计和合计

  • 本文关键字:jquery 添加 bfore jquery
  • 更新时间 :
  • 英文 :


编辑:这个问题被问了很多。以下是了解活动授权的链接。直接的答案是使用.on('event','selector',function);在我的例子中,它是$("fieldset").on('keyup','.line input',multInput);


我正在构建一个发票,允许用户通过单击按钮添加额外的服务付款行。每条服务线都有一个小计。

我遇到的问题是,我无法让小计为动态添加jQuery.forer.的字段工作

这是我的发票表格,带有添加另一行的按钮:

<div class="control-group">
     <label class="control-label"> Service</label><div class="controls form-inline">
      <div class="line">
       <input type="text" class="span3" id="serivceName" placeholder="Service name">
       <input type="text" class="qty span1" id="qty" placeholder="qty">
       <input type="text" class="price input-small" name="cost" id="service" placeholder="Price">
       <input type="text" class="subtotal" id="sub" name="sub" value="">
      </div>
     </div>
  </div>
 <div class="serviceHelper"></div> 
       <br />
       <br />
 <div class="pull-right span2">
      Total: <span id="income_sum" class="g_total"/>
       </div>
       <div>
      <a  id='addService' class="btn btn-success btn-small">Add another Product or Service</a><br />
                    </div>

以下是jQuery中的小计函数:

$(".line input").keyup(multInputs);
function multInputs() {
   var mult = 0;
      //iterate through the .line div and find values
   $(".line").each(function () {    
       var $val1 = $('.qty', this).val();
       var $val2 = $('.price', this).val();
       var $total = $val1 * $val2;
         //make the subtotal input equal the total var
       $(this).find(".subtotal").val($total);
         //add the subtotals together to make the invoice total
       var $form = $('#wizard');
       var $summands = $form.find('.subtotal');
       var $sumDisplay = $('#income_sum');
       var $sum = 0;
       $summands.each(function ()
        {
            var value = Number($(this).val());
            if (!isNaN(value)) $sum += value;
        });
    $sumDisplay.text(sum);
    });
}

用户添加的发票行是页面上已经存在的控制组的副本,但由于我正在将其插入jQuery Steps向导,因此进行了修改。

    $("#addService").click(function(){
    $(".serviceHelper").before("<div class='control-group'> <div class='controls form-inline'>"+
       "<div class='line'>"+
       "<input type='text' class='span3' id='serivceName' placeholder='Service name'> "+
       "<input type='text' class='qty span1' id='qty' placeholder='qty'> "+
       "<input type='text' class='price input-small' name='cost' id='service' placeholder='Price'> "+
       "<input type='text' class='subtotal' id='sub' name='sub' value=''>"+
       "</div> </div> </div>");
     });

你明白为什么小计适用于页面上的输入,而不适用于动态添加的输入吗?TIA

jQuery在运行时只知道页面中的元素,因此添加到DOM中的新元素无法被jQuery识别。为了解决这个问题,您必须使用事件委派,从新添加的项中冒泡事件,直到jQuery在页面加载时运行时DOM中的某个点。许多人使用document作为捕捉冒泡事件的地方,但没有必要在DOM树上走那么高。当然,您应该委托给页面加载时存在的最近的父级。

$(document).on('keyup', ".line input", multInputs); 

.line input上的keyup现在冒泡到文档级别,并且可以在那里进行处理。

最新更新