【问题标题】:JavaScript multiple inputs onChangeJavaScript 多输入 onChange
【发布时间】:2012-04-14 08:22:01
【问题描述】:
我有一个问题。基于 Zend 框架的应用程序中有一个购物车(显示为表格)。每一行都是购物篮中的一个产品。每行都有两个表单字段:数量和价值(=价格*数量)。
我想使用 JavaScript 使用 onChange 事件按数量(价格*数量)更改值,但我不知道如何在行数 > 1 的情况下执行此操作。输入在 foreach 中给出在 Zend 视图中循环。
JavaScript 中有没有通用算法来解决这个问题?
【问题讨论】:
标签:
javascript
input
onchange
【解决方案1】:
是否每个值字段都有例如可以从数量字段的 ID 派生的 ID 属性?如果是这样,那么它非常快速且无痛。给定:
<table id="basket">
<tr class="basket-row">
<td class="basket-quantity">
<input type="text" id="product1234_quantity">
</td>
<td class="basket-subtotal">
<input type="hidden" id="product1234_unitprice" value="20">
<input type="text" readonly="readonly" id="product1234_subtotal">
</td>
</tr>
<tr class="basket-row">
<td class="basket-quantity">
<input type="text" id="product5678_quantity">
</td>
<td class="basket-subtotal">
<input type="hidden" id="product5678_unitprice" value="30">
<input type="text" readonly="readonly" id="product5678_subtotal">
</td>
</tr>
</table>
这里,每个产品的单价都在一个隐藏属性中,但我不知道你的购物车存放在哪里。让我们假设你可以从某个地方得到它,让我们假设 jQuery。
$('#basket').on('change','.basket-quantity input',function(e) {
$('#'+this.id.replace('_quantity','_subtotal')).val(Number($('#'this.id.replace('_quantity','_unitprice')))*Number(this.value));
});
如果您不能从其他 ID 派生 ID,则必须进行一些更复杂的 DOM 查询,但关键是,在处理程序运行时,您必须确定要更新的输入。
您没有指定您正在使用什么(如果有)框架。在纯 JS 中,这将需要大量额外的代码来使其跨浏览器兼容,以规范事件附件和处理。
【解决方案2】:
在每个你可以使用的地方
$(this).index()
例如
$("#jieguo_qian table tr:nth-child(4) td").each(function(){
var tindex = $(this).index() + 1;
所以你可以在 diff tr 中获得相同的 td
th th th
td td td
td td td