【问题标题】:Assign a Value to a HTML Table Cell using JQuery使用 JQuery 为 HTML 表格单元格赋值
【发布时间】: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


【解决方案1】:

$i 是文本框,因此要获得它的值,您需要使用$i.val()。其他元素是表格单元格,因此要获取或设置您需要的值.text(),而不是.val()。但是,您使用 id 属性会使代码过于复杂。相反,删除 then 并使用相对选择器

$('input').keyup(function() { // or $('.nInput').keyup
  var i = Number$(this).val());
  var cells = $(this).closest('tr').children('td');

  var tp = cells.eq(3);
  var fp = cells.eq(6);
  // Get current cell values as a number
  var nt = Number(cells.eq(1).text());
  var nh = Number(cells.eq(2).text());
  var f = Number(cells.eq(5).text());
  // Update totals
  tp.text(nh + i - nt);
  fp.text(nh + i - f);

});

旁注:var i = $(this).val(); 的值可能是 null,但不确定您要如何处理 - 可能只是使用

var i = $(this).val();
if (!i) {
  return; // don't do any calculations
}

【讨论】:

  • 我更喜欢这个而不是我懒惰的答案,但我会更改硬编码的单元格索引,因为它可能会随着单元格的添加、删除或重新排序而变得脆弱。我建议在行的上下文中使用类或$('[id^=ntposition]')
  • 谢谢斯蒂芬·穆克!两个总数显示“NaN”错误,但我正在查看它。
  • @jle, 添加一些console.log() 语句以打印出intnhf 的值,以确保它们实际上是数字。你真的想要.keyup()吗?我怀疑应该是.change()
  • 是的,.change() 也可以。我将测试这两种体验。 console.log() 将 i 显示为和 int,但 nt、nh 和 f 是“NaN”。在模型中,这些字段是 int?类型。这可能是为什么它们在表中读取为数字但不能t 通过脚本中的 Number() 转换?
  • 您必须给出一些返回NAN 的表格单元格中的值的示例。如果属性是int? 并且没有值,那么Number() 返回0 所以应该没有问题,所以单元格中的实际值存在一些问题。
【解决方案2】:

你需要知道val()text()html()的区别

  • val() 用于获取和设置表单元素的值,inputselect 等。
  • text() 用于获取和设置非表单元素的纯无格式文本。
  • html() 用于从节点获取和设置内部 Html

所以你想要的是:

$tp.text($nh.text() + $i.val() - $nt.text());
$fp.text($nh.text() + $i.val() - $f.text());

还要小心,因为+ 是 javascript 中的数学加法 字符串连接,因此您可能希望将解析的字符串转换为适当的数字类型。

【讨论】:

  • 谢谢 Jon P - 这是一个很好的答案。在加法中涉及的文本值上使用 parseInt 时,我正在与基数作斗争,但这似乎可以解决问题。
猜你喜欢
  • 2013-12-11
  • 2011-01-24
  • 1970-01-01
  • 2012-06-15
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多