我有一个有效的文本框乘法,但是,当我添加一个新文本框时,该功能将不会执行。我制作的 js 函数仅执行第一个文本框。很抱歉问这个问题,但我对 jsquery/javascript 还很陌生。
这是我的工作脚本:JS FIDDLE
What it does is, I have a table and 2 TR on it. it multiply the cost(3rd td) and the quantity(fourth td) and send the results to the line total (fifth td). Then I have a button, that will add another set of tr to the existing table, however, the multiplication wont work on the newly added tr.
你能帮我吗?
TIA,
尼米兹
最佳答案
只需将这两行添加为 .click(...) 处理程序的最后两行:
$(".qty :input").off('keyup',byPrice).on('keyup',byPrice)
$(".price :input").off('keyup',byQty).on('keyup',byQty);
此处已更新 JSFiddle
原因是 - 您必须为新创建的行重新注册事件监听器。 您可以使用相同的选择器,但是您必须“关闭”以前的事件监听器。
更新
另一种方法是您只能在新创建的行上绑定(bind)事件: 这是另一个JSFiddle for that
您必须将新创建的行的内容放入某个变量中:
$('#myinvoice tr:last').after($newRow = $('<tr><td>...'));
然后仅在 $newRow 内为选择器添加事件:
$(".qty :input",$newRow).keyup(byPrice);
$(".price :input",$newRow).keyup(byQty);
我会用第二个
关于javascript - 动态元素的文本框事件处理程序的 jQuery 乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26162357/