4

考虑以下 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"/>

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

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

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

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

4

2 回答 2

8

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

$(document).ready(function() {
    $('input[name=post_id]').val($('#_postid').val());
});
于 2013-09-03T01:34:28.840 回答
1

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 input inside of a form with the name attribute set to post_id.

于 2013-09-03T01:34:03.053 回答