我误以为脚本。当我改变总价值时,我想改变利润中的价值。但这不正常。当我再次点击输入时,利润输入中的值会发生变化。
HTML:
<table>
<tr>
<td> <input class="price" name="price" value="50"/> </td>
<td>
<input class="profit" name="profit" value="10"/>
</td>
<td>
<select name="profit_type" class="profit_type">
<option value="$">$</option>
<option value="%">%</option>
</select>
</td>
<td>
<input class="total" name="total" value="60"/>
</td>
</tr>
<tr>
<td> <input class="price" name="price" value="50"/> </td>
<td>
<input class="profit" name="profit" value="20"/>
</td>
<td>
<select name="profit_type" class="profit_type">
<option value="$">$</option>
<option value="%">%</option>
</select>
</td>
<td>
<input class="total" name="total" value="70"/>
</td>
</tr>
</table>
JS:
$('table tr').on('click', function(e) {
var that = $(e.target);
var tableRow = $(this);
if (that.is('.total')) {
var price = parseFloat(tableRow.find('.price').val());
var total = parseFloat(tableRow.find('.total').val());
var profit_type = parseFloat(tableRow.find('.profit_type').val());
var profit = parseFloat(tableRow.find('.profit').val());
console.log(total);
if(profit_type == '%'){
profit = ((total - price)/price)*100;
}else{
profit = total - price;
}
tableRow.find('.profit').val(profit);
}
});
答案 0 :(得分:2)
只需在总输入上定位change
事件,而不是点击整个行。其他几乎不需要改变(假设其他逻辑是正确的)只是前两行:
$('.total').on('change',function(){
var $total= $(this);
var $tableRow = $total.parents('tr');
var price = parseFloat($tableRow.find('.price').val());
var total = parseFloat($total.val());
var profit_type = parseFloat($tableRow.find('.profit_type').val());
var profit = parseFloat($tableRow.find('.profit').val());
console.log(total);
if(profit_type == '%'){
profit = ((total - price)/price)*100;
}else{
profit = total - price;
}
$tableRow.find('.profit').val(profit);
});
实例:http://jsfiddle.net/uTqMk/2/
如评论所述,当profit_type
选择框也发生变化时,你想要做同样的事情,在这种情况下,你可以重构两者的行为相同:
$('.total, .profit_type').on('change',function(){
var $tableRow = $(this).parents('tr');
var price = parseFloat($tableRow.find('.price').val());
var total = parseFloat($tableRow.find('.total').val());
var profit_type = $tableRow.find('.profit_type').val();
var profit = parseFloat($tableRow.find('.profit').val());
console.log(total);
if(profit_type == '%'){
profit = ((total - price)/price)*100;
}else{
profit = total - price;
}
$tableRow.find('.profit').val(profit);
});
答案 1 :(得分:1)
试试这个
$(function(){
$('table tr').on('change', function(e) {
var tableRow = $(this);
var price = parseFloat(tableRow.find('.price').val());
var total = parseFloat(tableRow.find('.total').val());
var profit_type = (tableRow.find('.profit_type').val());
var profit = parseFloat(tableRow.find('.profit').val());
console.log(profit_type);
console.log(total);
console.log(profit_type);
if(profit_type == '%'){
profit = ((total - price)/price)*100;
}else{
profit = total - price;
}
tableRow.find('.profit').val(profit);
});
});
答案 2 :(得分:0)
为什么你不能尝试更改事件。这里的问题是你在表行上使用click事件,再次单击表行时,更改会受到影响。 因此,将其更改为“更改”事件或直接尝试从文本框中获取输入,计算结果并在利润文本框中显示。