javascript jQuery 获取此表单输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3468530/
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
jQuery get THIS form input
提问by Becky
I am trying to get the values of multiple form inputs, but the problem is I have several identical forms on the same page and only want to get the inputs from the form that was submitted, so I am using the 'this' keyword. This is my code:
我试图获取多个表单输入的值,但问题是我在同一页面上有几个相同的表单,只想从提交的表单中获取输入,所以我使用了“this”关键字。这是我的代码:
$('form.contact_form').submit(function(e) {
var fname = $(this).children('input.fname').val();
var email = $(this).children('input.email').val();
var comment = $(this).children('input.comment').val();
However, when I try to log the variables to test they're returning the wrong values, it says they are all undefined. What would be the right way to do this?
但是,当我尝试记录变量以测试它们返回错误的值时,它说它们都是未定义的。这样做的正确方法是什么?
Thanks for any help :D
感谢您的帮助:D
回答by CaffGeek
Need to see the HTML.
需要查看 HTML。
But, are they direct children of the form?
Or should you be using .find, instead of .childrenbecause they are nested lower?
但是,它们是形式的直接子级吗?
或者你应该使用.find, 而不是.children因为它们嵌套得较低?
回答by IcanDivideBy0
you can even use 'this' context
你甚至可以使用“this”上下文
var fname = $('input.fname', this).val();
回答by UpHelix
Use .find() as Chad suggested.
按照乍得的建议使用 .find() 。
$('form.contact_form').submit(function(e) {
var $this = $(this);
var fname = $this.find('input.fname').val();
var email = $this.find('input.email').val();
var comment = $this.find('input.comment').val();
});
回答by user45678
For later versions of jQuery. I'm using >3.0
对于更高版本的 jQuery。我正在使用 >3.0
var fname = $(this,''input.fname'').val();
I'm adding this because none of the other answers worked for me until I solved it myself. Hope it can also help you. Cheers
我添加这个是因为在我自己解决之前没有其他答案对我有用。希望它也能帮到你。干杯

