【发布时间】:2015-09-15 11:04:02
【问题描述】:
有一个表格显示模型条目,每个字段指定一个唯一的 div id,结合关键字和每一行的 ID。当用户在表格的输入列中输入一个数字时,脚本应该: 获取同一行中单元格的位置;并根据其他单元格的值改变两个预定单元格的值。 在最终更新之前,测试似乎是成功的。我尝试过使用 .val()、.value 和 .html(),结果单元格变为空白,如果脚本没有错误,则显示 0。有人可以发布正确的 jQuery 命令以及它为什么有效吗?非常感谢。
桌子:
<table id="dt_Positions" class="table table-striped">
<thead>
<tr>
<th class="text-center">Month</th>
<th class="text-center">Owed</th>
<th class="text-center">Bought</th>
<th class="text-center">Total Position</th>
<th class="text-center">Non-Fixed</th>
<th class="text-center">Fixed</th>
<th class="text-center">Fixed Position</th>
<th class="text-center">Proposed</th>
</tr>
</thead>
<tbody>
@if (Model.Forecasts.Any())
{
foreach (var record in Model.Summaries)
{
<tr>
<td id="nmonth@(record.fID)" align="center">@String.Format("{0:d}", @record.Month)</td>
<td id="ntotal@(record.fID)" align="center">@record.NTotal</td>
<td id="nbought@(record.fID)" align="center">@record.NBought</td>
<td id="ntposition@(record.fID)" align="center">@record.NTotalPosition</td>
<td id="nvariable@(record.fID)" align="center">@record.NVariable</td>
<td id="nfixed@(record.fID)" align="center">@record.NFixed</td>
<td id="nfposition@(record.fID)" align="center">@record.NFPosition</td>
<td id="ninput@(record.fID)" align="center"><input class="nInput" type="number" name="quantity" min="1" max="50000"></td>
</tr>
}
}
</tbody>
</table>
脚本:
@section Scripts
{
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script type="text/javascript" language="javascript">
$(function () {
$('[id^=ninput]').keyup(function (e) {
var $id = $(this).attr('id');
var $i = $(this);
var $idNum = $id.slice(6);
var $tp = $('#ntposition' + $idNum);
var $fp = $('#nfposition' + $idNum);
var $nt = $('#ntotal' + $idNum);
var $nh = $('#nbought' + $idNum);
var $f = $('#nfixed' + $idNum);
//The lines below appear to be the hiccup
$tp.val($nh.val() + $i.html() - $nt.val());
$fp.val($nh.val() + $i.html() - $f.val());
debugger;
});
});
</script>
}
编辑: 返回“NaN”的 id 示例如下: ntotal = 29, nbought = 5, ntposition = -24, nvariable = 3, nfixed = 26, nfposition = -21,从测试视图中看起来都是 int,但 ntotal、nbought 和 nfixed 在console.log 并导致在 ninput = 5 后测试视图中出现“NaN”。
【问题讨论】:
-
这里没有必要使用
id属性(这样做只会使您的代码过于复杂)。使用相对选择器 -$('input').keyup(function() { var cells = $(this).closest('tr').children('td');然后您可以使用var nh = cells.eq(2).text();等访问单元格的值(注意它的text()不是val()) -
谢谢斯蒂芬·穆克。我是 jQuery 中的相对选择器的新手,所以我会看看。
标签: javascript jquery html asp.net-mvc