jquery 在另一个旁边查找元素

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

jquery find element next to another

jquery

提问by thiagoleite

Hi I have the following html:

嗨,我有以下 html:

<p>  
    <input type="text" name="field1"/> <input type="hidden" name="fieldh1"/>  
    <button type="button" class="sendInfo">Send</button>  
</p>  
<p>  
    <input type="text" name="field2" /> <input type="hidden" name="fieldh2"/>  
    <button type="button" class="sendInfo">Send</button>  
</p>  

What I want is that when user clicks the button, I need to send using ajax the contents of the field field.

我想要的是,当用户单击按钮时,我需要使用 ajax 发送字段字段的内容。

This is what i'm trying to do with no success.

这就是我试图做但没有成功的事情。

$(function() {
        $('button.sendInfo').live('click', function() {
            var id = $(this).parent().next('[type=text]').val();
            alert(id);
        });
    });

I plan to set what the user types in textbox to the hidden field, and the value received from the ajax call to normal textbox. But the problem is that i can′t even get the value of the textbox that is in the same line as the button the user clicks. Can anyone help me? Thanks a lot.

我计划将用户在文本框中键入的内容设置为隐藏字段,并将从 ajax 调用接收到的值设置为普通文本框。但问题是我什至无法获取与用户单击的按钮位于同一行的文本框的值。谁能帮我?非常感谢。

回答by karim79

Try:

尝试:

$(this).siblings('input:text').val();

Or change nextto find:

或更改nextfind

$(this).parent().find('[type=text]').val();

as nextonly searches the immediate following sibling.

asnext只搜索紧随其后的兄弟

回答by cyberw0lf

I can use jQuery.next()function.

我可以使用jQuery.next()功能。

回答by Jacob Mattison

Your issue is that "next()" is going to the next sibling of the parent -- and the parent is the <p>tag, so the sibling, if it exists, is the following <p>tag.

您的问题是“next()”将转到父项的下一个兄弟节点——父项是<p>标记,因此兄弟项(如果存在)是以下<p>标记。

You want $(this).parent().children('[type=text]').val()or $(this).parent().find('[type=text]')

你想要$(this).parent().children('[type=text]').val()$(this).parent().find('[type=text]')

回答by Rbacarin

Can you select your textbox using id ?

您可以使用 id 选择您的文本框吗?

$(function() { 
   $('button.sendInfo').live('click', function() {
      //what about this:
      var id = $('#textBoxID').val();
      alert(id); 
       //or this
      var id2 = $('+ input', this).val(); 
      alert(id2);
    }); 
});