此代码将产生10行文本框1、文本框2和文本框3。如果我在loop1中的文本框的第一行中输入值。例如1和3,它将相乘,结果为3。但是随后它将在所有循环中显示结果。我怎么能只在环1中完成呢。?
示例
QTY PRICE AMOUNT
line1 1 2 3
line2 3
line3 3
line4 3
line5 3
line6 3
line7 3
line8 3
line9 3
line10 3
PHP-HTML代码
<?php for($x=1; $x<=10; $x++){?>
<tr>
<td><input type="text" name="qty<?=$x;?>" class="qty form-control" size="6"/></td>
<td><input type="text" name="price<?=$x;?>" class="price form-control" /></td>
<td><input type="text" name="amount<?=$x;?>" class="amount form-control"></td>
</tr>
<?php } ?>
JS代码
<script>
$(".price,.qty").keyup(function () {
$('.amount').val($('.qty').val() * $('.price').val());
});
</script>
如果你为每个事件单独编写,这将非常容易。试试这个,
<script>
$(document).ready(function(){
$(".qty").keyup(function () {
$(this).closest('tr').find('.amount').val($(this).val() * $(this).closest('tr').find('.price').val());
});
$(".price").keyup(function () {
$(this).closest('tr').find('.amount').val($(this).closest('tr').find('.qty').val() * $(this).val());
});
});
</script>
<script>
$(".price,.qty").keyup(function () {
var curName = $(this).attr('name');
var reqName = '';
if (curName.indexOf("qty") != -1) {
reqName = curName.substr(3);
} else {
reqName = curName.substr(5);
}
$("input[name='amount"+reqName+"']").val($("input[name='qty"+reqName+"']").val() * $("input[name='price"+reqName+"']").val());
});
</script>
我解决了它。。我只是更改它,而不是使用类I使用ID,然后将变量x放在ID中,并将变量x放到我的JS 上
<?php for($x=1; $x<=10; $x++){?>
<tr>
<td><input type="text" name="qty<?=$x;?>" id="qty<?=$x;?>" class="form-control" size="6"/></td>
<td><input type="text" name="price<?=$x;?>" id="price<?=$x;?>" class="orm-control" /></td>
<td><input type="text" name="amount<?=$x;?>" id="amount<?=$x;?>" class="form-control"></td>
</tr>
<?php } ?>
$("#price<?=$x;?>,#qty<?=$x;?>").keyup(function () {
$('#amount<?=$x;?>').val($('#qty<?=$x;?>').val() * $('#price<?=$x;?>').val());
});