jQuery:找到最靠近按钮的输入字段

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

jQuery: find input field closest to button

jqueryhtmlclosestform-fields

提问by user2571510

I have a large HTML form with multiple input fields (one in each row). Among these I have several fields with a specific class that appear left from a button. There are no other buttons or fields in these rows so they only contain the field and button as below.

我有一个包含多个输入字段(每行一个)的大型 HTML 表单。其中我有几个具有特定类的字段,它们出现在按钮的左侧。这些行中没有其他按钮或字段,因此它们仅包含如下所示的字段和按钮。

How can I get the ID of such a field when clicking on the button right from it, i.e. closest to it ?

单击右侧的按钮(即最接近它)时,如何获取此类字段的 ID?

All fields in question look like this:

有问题的所有字段如下所示:

<input type="text" class="dateField" data-date-format="yyyy-mm-dd" id="field1" name="field1" />

All buttons in question look like this:

所有有问题的按钮看起来像这样:

<button type="button">Select Date</button>

Thanks for any help with this, Tim.

感谢您对此的任何帮助,蒂姆。

回答by MonkeyZeus

Because <input>is to the left of <button>you can find it like this:

因为<input>在左边<button>你可以这样找到它:

$('button').on('click', function(){
    alert($(this).prev('input').attr('id'));
});


If <input>was after <button>then you can find it like this:

如果<input><button>之后,您可以像这样找到它:

$('button').on('click', function(){
    alert($(this).next('input').attr('id'));
});

回答by Adil

You can go to parent of button using parent()and the find the input in descendants using find()

您可以使用使用转到按钮的父级parent()并使用在后代中查找输入find()

OR, if you have multi-level descendant

或者,如果您有多级后代

$(this).parent().find('.dateField')

OR, if you have single level descendants

或者,如果您有单级后代

$(this).parent().children('.dateField')

or

或者

$(this).siblings('.dateField');

Similarly you can use next()or prev()

同样,您可以使用next()prev()

回答by sPaz

Use .prev()or .next()if they're next to each other. (This should be fastest.) Otherwise you can also use .closest()to simply find closest instance of that class.

如果它们彼此相邻,请使用.prev().next()。(这应该是最快的。)否则您也可以使用.closest()来简单地找到该类的最近实例。

The documentation should be more than enough help.

文档应该有足够的帮助。

Edit:You can also use .siblings()to search through siblings of that element.

编辑:您还可以使用.siblings()搜索该元素的兄弟姐妹。