javascript jQuery选择下一个表格行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13402877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:39:42  来源:igfitidea点击:

jQuery to select next table row

javascriptjquery

提问by mrtonyb

I have two rows of a table here. When I click the checkbox in the first table row, I'm trying to target the ID of the span in the next table row. I have an alert in my code just to show me that I was successful.

我这里有两排桌子。当我单击第一个表格行中的复选框时,我试图将跨度的 ID 定位到下一个表格行中。我的代码中有一个警报只是为了告诉我我成功了。

What I have isn't working. I can't figure out a way to select data in the next table row when the checkbox in the first row is clicked.

我所拥有的不起作用。单击第一行中的复选框时,我无法找出在下一个表格行中选择数据的方法。

<table>
<tr id="row-a">
<td>
    <input type="checkbox">
    <span>
        some text
    </span>
</td>
</tr>
<tr>
<td>
    <span id="target">
        some text
    </span>
</td>
</tr>
</table>

$(document).ready(function() {
   var myCheck = $("tr#row-a td input");

   myCheck.change(function(){
   var spanID = $("tr#row-a').next('tr').find('span').attr('id');
   alert(spanID);
   });
});

回答by Rory McCrossan

Try this:

试试这个:

var myCheck = $("tr#row-a td input");
myCheck.change(function(){
    var spanID = $(this).closest('tr').next().find('span').attr('id');
    alert(spanID);
});

Example fiddle

示例小提琴

回答by Adriano Carneiro

$(document).ready(function() {
   var myCheck = $("tr#row-a td input");

   myCheck.change(function(){
   var spanID = myCheck.parents("tr").next().find('span').attr('id');
   alert(spanID);
   });
});

The change was in this line:

变化在这一行:

   var spanID = myCheck.parents("tr").next().find('span').attr('id');

Which does the following:

执行以下操作:

  • Finds the checkbox's trparent
  • Gets the next sibling node (next tr)
  • Finds the span
  • Gets its id
  • 查找复选框的tr父级
  • 获取下一个兄弟节点(next tr
  • 找到 span
  • 获取它的 id