javascript 在 JQuery 中,如何获取相邻的表格单元格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3915325/
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-25 02:41:17  来源:igfitidea点击:

In JQuery how can I get the adjacent table cell?

javascriptjquery

提问by NibblyPig

I have a table with multiple rows, and each row contains three cells. Each cell contains a textbox, so it looks like this:

我有一个多行的表格,每行包含三个单元格。每个单元格都包含一个文本框,所以它看起来像这样:

XXXX   XXXX   XXXX

on the keyup event of the first textbox, I want its contents to be copied into the second textbox, but not the third textbox.

在第一个文本框的 keyup 事件上,我希望将其内容复制到第二个文本框,而不是第三个文本框。

my keyup event I can get a reference to the first textbox. Doing .parent() will give me the cell, and if I want, doing .parent() again will give me the row.

我的 keyup 事件我可以获得对第一个文本框的引用。执行 .parent() 会给我单元格,如果我愿意,再次执行 .parent() 会给我行。

What JQuery can I use to get the adjacent textbox?

我可以使用什么 JQuery 来获取相邻的文本框?

回答by Nick Craver

You can use .next()to get the next sibling, like this:

您可以使用.next()获取下一个兄弟姐妹,如下所示:

var nextTD = $(this).closest("td").next();
//for your case:
$(this).closest("td").next().find("input").val($(this).val());

.parent()works too, .closest()is just a bit more flexible, for you could change your markup and it'd still go to the nearest <td>parent.

.parent()也可以工作,.closest()只是更灵活一点,因为您可以更改标记,但它仍然会转到最近的<td>父级。

回答by user113716

From the .parent()<td>, use next()to go to the next <td>, then .children('input')to get the child <input>element.

从, 使用转到下一个,然后获取子元素。.parent()<td>next()<td>.children('input')<input>

So you end up with something like this in your keyuphandler.

所以你最终在你的keyup处理程序中得到了这样的东西。

$(this).parent().next().children('input').val( this.value );

回答by Tim S. Van Haren

Give the next()function a try. This selects the next sibling of the selected element.

next()试试这个功能。这将选择所选元素的下一个兄弟元素。