jQuery 如何获取最近输入Jquery的值

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

How to get value of nearest input Jquery

jqueryclosest

提问by user342391

I have multiple buttons on my page with the same class. When I click on a button I want to get the value of the nearest input box (remember there are multiple input boxes and buttons on my page with the same classes).

我的页面上有多个具有相同类的按钮。当我单击一个按钮时,我想获取最近输入框的值(请记住,我的页面上有多个输入框和按钮具有相同的类)。

I have:

我有:

    $(".deletepostbutton").click(function() {

            var deleteid = $(this).closest('.deleteid').attr('value');

  });


<div class="microblogpostactions">
     <input type="text"  name="deleteid" class="deleteid" value="'.$row['id'].'" />
     <a href="Javascript:void[0]" class="deletepostbutton">Delete</a>
     </div>

<div class="microblogpostactions">
     <input type="text"  name="deleteid" class="deleteid" value="'.$row['id'].'" />
     <a href="Javascript:void[0]" class="deletepostbutton">Delete</a>
     </div>

How can I get the value of the nearest input and make my variable equal to it when a user clicks on the link????

当用户单击链接时,如何获取最近输入的值并使我的变量等于它????

回答by user113716

Use .prev()if you're sure they're right next to each other. (This should be fastest.)

使用.prev()如果你确定他们是对彼此相邻。(这应该是最快的。)

 var deleteid = $(this).prev().attr('value');

This gets the previous element.

这将获取前一个元素。

If there's a chance that there will be another element in between, you could use .siblings():

如果两者之间有可能会有另一个元素,您可以使用.siblings()

 var deleteid = $(this).siblings('.deleteid').attr('value');

This will get allsiblings inside the same <div>with the deleteidclass.

这将让所有的兄弟姐妹中的一样<div>deleteid类。

回答by Alex Reitbort

$(this).parent().find('.deleteid').attr('value');

回答by Dmitry Zaytsev

$(this).parent().find('.deleteid').attr('value');

It may (and it does) cause problems with perfomance. For example:

它可能(并且确实)会导致性能问题。例如:

$(this).parent().find('.deleteid').val(10);
alert($(this).parent().find('.deleteid').val());

Sometimes it returns the previous value of .deleteid (not 10)

有时它会返回 .deleteid 的先前值(不是 10)