編輯:這個問題被問了很多。這裏是understanding event delegation的鏈接。直接的答案是使用.on('event','selector',function);在我的情況是$(「fieldset」)。on('keyup','.line input',multInputs);在jquery中添加輸入時的小計和總數。
我正在構建一個發票,允許用戶通過單擊按鈕添加額外的服務支付線。每一行服務都有一個小計。
我遇到的問題是,我無法讓小計工作在使用jQuery .before動態添加的字段中。
這是我的發票的形式,與該按鈕來添加另一行:
<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
這個問題被問了很多次。對於動態創建的元素,使用帶有[.on()](http://api.jquery.com/on/)的委託事件處理程序。例如''('。control-group')。on('keyup',「.line input」,multInputs);' – Regent 2014-10-17 12:09:23
事實上它每天會被詢問很多次!閱讀事件代表團 – charlietfl 2014-10-17 12:16:05