jQuery:在 while 循环内形成表单
我在 PHP 的 while 循环中有一个表单。有 action="javascript:block_grade($id)",但是当我在 block_grade 函数中发出警报(id)或警报(lvl)时,我从所有循环中收到相同的数字?
这是我的循环内部:
echo '<form action="javascript:block_grade('.$show['id'].')" method="post">';
echo 'Change blockgrade: ';
echo '<input type="text" name="lvl" size="1" value="'.$show['lvl'].'">';
echo '<input type="submit" value="Save">';
echo '</form>';
这是我的底部函数:
<script>
function block_grade ( id ) {
var lvl = $('input[name=lvl]').val();
alert(lvl);
alert(id);
}
</script>
我该如何解决这个问题,还有比这更有效的方法吗?
I have a form inside a while loop in PHP. There is action="javascript:block_grade($id)", but when i alert(id) or alert(lvl) in the block_grade function, I receive the same numbers from all the the loops?
This is inside my loop:
echo '<form action="javascript:block_grade('.$show['id'].')" method="post">';
echo 'Change blockgrade: ';
echo '<input type="text" name="lvl" size="1" value="'.$show['lvl'].'">';
echo '<input type="submit" value="Save">';
echo '</form>';
This is my function at bottom:
<script>
function block_grade ( id ) {
var lvl = $('input[name=lvl]').val();
alert(lvl);
alert(id);
}
</script>
How can I solve this, and is there any more effective way than this, maybe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我更希望看到 JavaScript 直接附加事件处理程序,然后您可以轻松地执行与表单相关的操作。
然后:
除了其他优点之外,这还释放了
action
属性,因此您可以填写一个脚本,无需 JavaScript 即可在必要时直接处理此请求。但更重要的是(您原来的问题),它确保您查看的是正确
lvl
字段,而不仅仅是第一个lvl
字段 jQuery 碰巧在 DOM 中遇到。I'd prefer to see JavaScript attach the event handler directly and then you can easily do things relative to the form.
Then:
Among other advantages, this frees up the
action
property so you can fill in a script that can directly process this request without JavaScript if necessary.But more to the point (of your original question), it ensures that you're looking at the correct
lvl
field, and not just the firstlvl
field jQuery happens to come across in the DOM.我什至不知道可以将表单的操作设置为“javascript:...”。我总是使用
onsubmit
事件。不管怎样,对于
lvl
来说,难怪你总是得到相同的结果,因为val()
给出了集合中第一个元素的值。该集合包含整个页面中的所有输入。但是,对于
id
您应该获得正确的值。也许您应该显示生成的最终 HTML。I didn't even know that it's possible to set the action of a form to "javascript: ...". I always use the
onsubmit
event.Anyway, for
lvl
it is no wonder you get always the same becauseval()
gives the value of the first element in the set. The set contains all theinput
s in the whole page.However, for
id
you should get the correct value. Maybe you should show the final HTML that is generated.