我正在尝试编写一些简单的HTML / jquery,它将相同的计算应用于不同的字段。
我已将问题简化为以下HTML:
// Check if a row in the current selection has a gray background color,
// so it can be skipped on Drag&Drop.
foreach(DataGridViewRow selectedRow in dgvToolPosition.SelectedRows)
{
if(selectedRow.DefaultCellStyle.BackColor == FCSCoreGlobal.ColorGray)
return;
}
和Jquery:
AllowDrag
但是这会根据第一行的数据条目为每一行返回相同的Result。我显然希望用户在每一行中输入不同的值,并且每行得到不同的结果。我尝试使用“each”和“$(this).children”如下,但它不起作用:
<h1>Multiplication by line</h1>
<table>
<tr>
<td>Number 1</td>
<td>Number 2</td>
<td>Result</td>
</tr>
<!-- LINE ITEM START -->
<div class="lineitem">
<tr>
<td>
<input type="number" name="a" class="a" value="" />
</td>
<td>
<input type="number" name="b" class="b" value="" />
</td>
<td>
<div class="total">0 </div>
</td>
</tr>
</div>
<!-- LINE ITEM END -->
<div class="lineitem">
<tr>
<td>
<input type="number" name="a" class="a" value="" />
</td>
<td>
<input type="number" name="b" class="b" value="" />
</td>
<td>
<div class="total">0</div>
</td>
</tr>
</div>
Here's a JSFiddle with everything.
真的希望有人可以帮忙!我已经做了相当多的搜索,但对这里的基本问题没有任何喜悦......如果这是一个重复道歉
答案 0 :(得分:1)
您的代码中的错误是您使用类来使用元素但您没有限制计算仅在所需的行上发生。所以修复方法是when ever there is a change in the input elements, find the closest tr in which it is wrapped , and now find the items within this tr and do the calculations.
更改您的函数以将计算限制为特定行。
function compute() {
var $parentTr = $(this).closest('tr'); // find the tr which wraps this element.
var a = $parentTr.find('.a').val();// find .a within this tr
var b = $parentTr.find('.b').val();// find .b within this tr
var total = (a * b);
$parentTr.find('.total').text(total);// change .total within this tr
}
答案 1 :(得分:0)
这可能会有所帮助。
$(document).ready(function() {
$('.a, .b').change(function() {
var tr = $(this).closest('tr');
var a = parseInt(tr.find('.a').val()) || 0;
var b = parseInt(tr.find('.b').val()) || 0;
tr.find('.total').html(a + b);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Multiplication by line</h1>
<table>
<tr>
<td>Number 1</td>
<td>Number 2</td>
<td>Result</td>
</tr>
<!-- LINE ITEM START -->
<div class="lineitem">
<tr>
<td>
<input type="number" name="a" class="a" value="" />
</td>
<td>
<input type="number" name="b" class="b" value="" />
</td>
<td>
<div class="total">0</div>
</td>
</tr>
</div>
<!-- LINE ITEM END -->
<div class="lineitem">
<tr>
<td>
<input type="number" name="a" class="a" value="" />
</td>
<td>
<input type="number" name="b" class="b" value="" />
</td>
<td>
<div class="total">0</div>
</td>
</tr>
</div>