代码之家  ›  专栏  ›  技术社区  ›  Jon

检索当前行的表行索引

  •  6
  • Jon  · 技术社区  · 15 年前

    当文本输入失去焦点时,我正在尝试验证它。我想知道它在桌子的哪一行。这就是我到目前为止所拥有的,而且它一直没有被定义。有什么想法吗?

    $("div#step-2 fieldset table tbody tr td input").blur(function() {
        var tableRow = $(this).parent().parent();
        if ($.trim($(this).val()) == "") {
            $(this).addClass("invalid");
            alert(tableRow.rowIndex);
            $(this).val("");
        } else {
            $(this).removeClass("invalid");
            checkTextChanges();
        }
    });
    
    4 回复  |  直到 8 年前
        1
  •  14
  •   bobince    15 年前

    rowIndex 是一个dom属性,而不是jquery方法,因此必须在底层dom对象上调用它:

    tableRow[0].rowIndex
    

    或者只是:

    var row= this.parentNode.parentNode;
    alert(row.rowIndex);
    

    因为在那里你并没有真正使用jquery。

    在jquery 1.4中 $(row).index() ,但它会扫描同级元素,找出它在父元素中的子元素编号。这比较慢,将返回不同的结果 行指数 如果你有多个 <tbody> 艾斯·S·S

        2
  •  2
  •   PetersenDidIt    15 年前

    使用jquery 1.4.*可以使用 index() method.

    你的选择器比需要的更具体一些。你也应该使用 closest 方法,而不是多个parent()调用。同时缓存$(this)。

    $("#step-2 fieldset table td input").blur(function() {
        var that = $(this),
            tableRow = that.closest('tr');
        if ($.trim(that.val()) == "") {
            that.addClass("invalid");
            alert(tableRow.index());
            that.val("");
        } else {
            that.removeClass("invalid");
            checkTextChanges();
        }
    });
    

    另外,alert不是一个很好的调试工具,可能是时候让您检查一下了 firebug

        3
  •  1
  •   janmoesen    15 年前

    您正在尝试对jquery对象使用dom core属性。试试这个:

    alert(tableRow[0].rowIndex);

    @Jandreas:来自W3C文档: rowIndex of type long, readonly, modified in DOM Level 2 这是逻辑顺序,而不是文档顺序。rowindex确实考虑了表中的部分(thead、tfoot或tbody),将thead行放在索引中的第一位,然后是tbody行,最后是tfoot行。

    .index() 不会把这些费用考虑在内。

        4
  •  0
  •   easement    15 年前

    尝试 closest('tr') 如果你是1.3+版本。它会比parent()工作得更好。