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

查找父类和ID

  •  2
  • Breezer  · 技术社区  · 16 年前

    好吧,经过无数次的尝试,我还是做不到这份工作?

    <script type="text/javascript">
        $("td input").focusout(function() {
          var column = $(this).parent('td').attr('class');
          var row = $(this).parent('tr').attr('id');
          $('#dat').HTML(row+" "+column);
        }); 
    </script>
    

    HTML看起来像这样

    <tr class="numbers" id="1">
    <td class="a" align="right">1</td>
    <td class="b"><input class="input" type="text" value=""/></td>
    <td class="c"><input class="input" type="text" value=""/></td>
    
    <td class="d"><input class="input" type="text" value=""/></td>
    <td class="e"><input class="input" type="text" value=""/></td>
    <td class="f">0</td>
    <td class="g"><input class="input" type="text" value=""/></td>
    </tr>
    

    有人能给我指出可能是什么问题的正确方向吗? 提前谢谢

    当做

    4 回复  |  直到 16 年前
        1
  •  2
  •   BrunoLM    16 年前

    注意它应该是小写的

    $('#dat').HTML(row+" "+column);
    

    .html

    $(this).parent('tr')
    

    为空,输入不能有父级tr

    除此之外,您还可以使用

    .closest( selector, [ context ] ) function

        2
  •  0
  •   Ken Redler    16 年前

    尝试:

    $(this).closest('td').attr('class')
    

    在代码的适当位置。身份证也是一样。

        3
  •  0
  •   ground5hark    16 年前

    您的代码在大多数情况下都是正确的,只需修复以下问题:

    $('#dat').HTML(row+' ' +column);
    

    对此:

    $('#dat').html(row + ' ' + column);
    

    而这:

    $(this).parent('tr').attr('id');
    

    对此:

    $(this).parents('tr').attr('id');
    
        4
  •  0
  •   Alastair Pitts    16 年前

    你想用 .parents() 函数而不是 .parent() .

    原因,从文件,我的重点。

    给定一个jquery对象,该对象表示 一组dom元素,.parent()。 方法允许我们搜索 DOM中这些元素的父级 树并构造一个新的jquery对象 来自匹配的元素。 这个 .parents()和.parent()方法是 类似,只是后者 在DOM上移动一个级别 树。