如何使用jquery在表中查找td的父tr?

Kar*_*idi 12 asp.net-mvc jquery

我正在使用asp.net mvc 3.我有以下结构,

<tr data-uid="123">
<td>
<a href="#" id="click">Click Me</a>
</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

现在我想找到标签数据属性值.我试过了,

$("a#click").click(function(){
 var i= $(this).parent('td').parent('tr').data('uid');
});
Run Code Online (Sandbox Code Playgroud)

但对我来说不起作用.请指导我.

Sus*_* -- 27

试试这个

$("#click").click(function(e){
    e.preventDefault();

    var $i = $(this).closest('tr').attr('data-uid');
    console.log($i);

    var $j = $(this).closest('tr').data('uid');
    console.log($j);
});?
Run Code Online (Sandbox Code Playgroud)

closest 只是为了防止默认操作..你可以删除它,如果你不需要它.

还要确保将e.preventDefault()其封装在表格标签内以使其正常工作.

骗子在这里


Jay*_*tel 12

回答

$("a#click").click(function(e){
    e.preventDefault();
    var i = $(this).closest('tr').attr('data-uid');
    console.log(i);
    var j = $(this).closest('tr').data('uid');
    console.log(j);
});
Run Code Online (Sandbox Code Playgroud)

查看演示


如何找到最近的行?

使用.closest():

var $row = $(this).closest("tr");
Run Code Online (Sandbox Code Playgroud)

使用.parent():

检查此.parent()方法.这是一个替代.prev().next().

var $row = $(this).parent()             // Moves up from <button> to <td>
                  .parent();            // Moves up from <td> to <tr>
Run Code Online (Sandbox Code Playgroud)

获取所有表格单元格 <td>

var $row = $(this).closest("tr"),       // Finds the closest row <tr> 
    $tds = $row.find("td");             // Finds all children <td> elements

$.each($tds, function() {               // Visits every single <td> element
    console.log($(this).text());        // Prints out the text within the <td>
});
Run Code Online (Sandbox Code Playgroud)

查看演示


只获得具体信息 <td>

var $row = $(this).closest("tr"),        // Finds the closest row <tr> 
    $tds = $row.find("td:nth-child(2)"); // Finds the 2nd <td> element

$.each($tds, function() {                // Visits every single <td> element
    console.log($(this).text());         // Prints out the text within the <td>
});
Run Code Online (Sandbox Code Playgroud)

查看演示


有用的方法

  • .closest() - 获取与选择器匹配的第一个元素
  • .parent() - 获取当前匹配元素集中每个元素的父元素
  • .parents() - 获取当前匹配元素集中每个元素的祖先
  • .children() - 获取匹配元素集中每个元素的子元素
  • .siblings() - 获取匹配元素集中每个元素的兄弟姐妹
  • .find() - 获取当前匹配元素集中每个元素的后代
  • .next() - 获得匹配元素集中每个元素的紧随其后的兄弟
  • .prev() - 获取匹配元素集中每个元素的前一个兄弟


Mic*_*ael 2

您的代码应该按原样工作,但您可以不使用多个 .parent() ,而应该使用parents(\'tr\')。http://api.jquery.com/parents/

\n\n
$(function() {\n  $("a#click").click(function(){\n    var i= $(this).parents(\'tr\').data(\'uid\');\n  });\xe2\x80\x8b\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

演示: http: //jsfiddle.net/mchambaud/G5jM8/1/

\n