jQuery: find input field closest to button

时光怂恿深爱的人放手 提交于 2019-11-28 09:44:42

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

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

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

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

You can go to parent of button using parent() and the find the input in descendants using 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()

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.

The documentation should be more than enough help.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!