javascript 使用jQuery设置具有相同ID的多个输入的值?

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

Setting the value of multiple inputs with the same id using jQuery?

javascriptjqueryhtml

提问by Mike Perrenoud

Considering the following HTML:

考虑以下 HTML:

<form id="upvoteForm" method="post" action="/post/upvote">
    <input type="text" name="post_id" id="post_id"/>
</form>
<form id="downvoteForm" method="post" action="/post/downvote">
    <input type="text" name="post_id" id="post_id"/>
</form>

<input type="hidden" id="_postid" value="1"/>

I'm trying to set the two inputfields with the name post_idto to value from _postidusing this JavaScript and jQuery:

我正在尝试使用此 JavaScript 和 jQueryinput将名称post_id为 to的两个字段设置为值_postid

$(document).ready(function() {
    $('#post_id').val($('#_postid').val());
});

However, as you can see in this jsFiddle, it's only setting the value of the first one. How do I set the value of both of them? I thought the selector would end up grabbing both.

但是,正如您在这个 jsFiddle 中看到的,它只是设置第一个的值。我如何设置它们的值?我认为选择器最终会同时抓住两者。

Now, I realize you might be wondering why I have two forms on this page. The basic reason is I have buttoninputs that I've styled the way I want but then I use the onclickto call the submitof the appropriate form here. I am ultimately going to be leveraging AJAX here, but that's coming later.

现在,我意识到你可能想知道为什么我在这个页面上有两个表格。基本原因是我有button输入,我已经按照我想要的方式设置了样式,但是我在这里使用onclick来调用submit适当形式的 。我最终将在这里利用 AJAX,但那会在以后出现。

回答by gp.

id is always unique. you cannot select 2 elements with same id. select by name

id 总是唯一的。您不能选择 2 个具有相同 ID 的元素。按名称选择

$(document).ready(function() {
    $('input[name=post_id]').val($('#_postid').val());
});

回答by Chris Hayes

Having two HTML elements with the same ID is illegal and will cause undefined behavior such as what you're experiencing. Using the same name is valid, however. Therefore you could use a selector like $('form > input[name=post_id]'), which would look for an inputinside of a formwith the nameattribute set to post_id.

拥有两个具有相同 ID 的 HTML 元素是非法的,并且会导致未定义的行为,例如您遇到的情况。但是,使用相同的名称是有效的。因此你可以使用像一个选择$('form > input[name=post_id]'),这将寻找一个input的内部formname属性设置为post_id