Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 返回到tr的引用_Javascript_Jquery - Fatal编程技术网

Javascript 返回到tr的引用

Javascript 返回到tr的引用,javascript,jquery,Javascript,Jquery,我得到了这样一个结果: <table> <tr> <td></td> <td></td> <td> <table> <tr> <td><a href="#" class="fav">click me</a></td> </tr&g

我得到了这样一个结果:

<table>
  <tr>
    <td></td>
    <td></td>
    <td>
       <table>
          <tr>
             <td><a href="#" class="fav">click me</a></td>
          </tr>
       </table>
    </td>
  </tr>
  ...
</table>
这给了我第二个表格中的
tr
(td中的表格)的参考。我想在我的初始表中获得对
tr
的引用。图中突出显示了我有参考的地方。箭头显示了我想在哪里获得参考

页面上还有很多其他表格。

您可以使用以下功能:

$(".fav").click(function(){
  var parentRow = $(this).parents("tr:eq(1)");
  // or $(this).parents("tr").eq(1);
  // or $($(this).parents("tr")[1]);
  // or $($(this).parents("tr").get(1));
});

您正在选择最接近的TR,即内部表中的TR。要获取外部表中最接近的TR,必须首先找到该外部表:

$(".fav").click(function(){
    var parentRow = $(this).closest('table').closest('tr');
});
只需找到父级的

使用以下命令:

var parentRow = $(this).closest('table').closest('tr');

如果您只需要外部父tr,请再次使用
最近('tr')
您可以将特定类添加到行中,然后使用$(this.nestest('tr.classname');这与
最近('tr')
有什么不同当您使用
父元素(选择器)
函数时,它将以数组的形式获取给定选择器中的所有父元素。在这种情况下,它的运行速度比循环通过所有同级节点的
最近的
函数快得多。这里的问题不是关于
性能的问题,而是关于
获得正确的tr元素
@Tushar它将获得正确的
tr
我已经多次使用过它。使用
$(this)。父('tr')。eq(1)
为了避免对$wouldthis进行双重包装,找到第二个表吗?
最近的
从内部到外部抓取DOM。你说的第二桌是什么意思?里面的还是外面的?这段代码首先找到内部表,然后继续搜索该内部表的父TR。它将在第一个表中找到TR。但是,如果您的表嵌套的深度超过一个,那么这并不总是有效的。@Krisholenbeck如果您不知道有多少个表嵌套在彼此之间,就不应该使用
最接近的
,因为这只是一个猜测。当处理数量未知的嵌套级别时,应该为最外层的表设置一个类名以供参考,然后向上走到一个TR,该TR是具有该类名的表的TBODY(隐式添加)的直接子级。@feeela,我同意。只要指出它,以防有人不知道。
$(".fav").click(function(){
  var parentRow = $(this).closest('tr').parents('tr')[0];
  console.log(parentRow)
});
var parentRow = $(this).closest('table').closest('tr');