gpt4 book ai didi

Javascript - 多次更改事件触发器

转载 作者:行者123 更新时间:2023-11-30 11:39:58 25 4
gpt4 key购买 nike

我有下表。

<table class="table invoice-items-table">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr class="invoice-item-row">
<td>
<select class="selectpicker invoice-item-select" title="Select an Item">
<option value="1">PHP Development</option>
</select>
</td>
<td class="text-right">
<input class="form-control invoice-item-quantity" value="1" type="text">
</td>
<td class="text-right">
<input class="form-control invoice-item-price" value="0.00" type="text">
</td>
<td class="text-right" style="padding-top:18px!important;">
<span class="invoice-item-amount">0 </span>
<span class="invoice-currency">₹</span>
</td>
</tr>
<tr class="invoice-item-add-row">
<td colspan="7">
<a href="#" class="link invoice-item-add text-center">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
Add an Item
</a>
</td>
</tr>
</tbody>
</table>

对于 a.invoice-item-add 的点击事件,我将更多表行 tr 添加到表中,这是相关代码。

$('.invoice-item-add').on('click', function() {
var itemRowClone = $('.invoice-item-row').last().clone();
itemRowClone.find('input, textarea').val('');
itemRowClone.find('.bootstrap-select').replaceWith(function() { return $('select', this); });
itemRowClone.find('.selectpicker').selectpicker();
$('.invoice-item-add-row').before(itemRowClone);
return false;
});

这工作得很好,直到我想触发 select.invoice-item-select,下面是我如何触发它。

$(document).on('change', '.invoice-item-select', function() {
// Code here...
});

我的问题是,如果有一个tr.invoice-item-row,它会根据动态添加的元素数量被触发多次,如果有,它会被触发两次两个 tr.invoice-item-row 它被触发了四次,基本上它触发了两次。

我知道 tr.invoice-item-row 是动态添加的,我们正在使用 $(document).on('change', '.invoice-item-select' , function()... 监听触发器。

我如何确保这个 on-change 事件只触发一次?

谢谢。

最佳答案

$(document).on('change') 事件应该在页面加载时调用一次。无需在添加行时添加文档更改。

您可以先取消绑定(bind)事件然后再绑定(bind)

$(document).off('change','.invoice-item-select').on('change', '.invoice-item-select', function() {
// Code here...
});

关于Javascript - 多次更改事件触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43113018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com