具有多种表单的表单插件 |提交返回最后一个表格
我正在编写自己的表单验证插件。我正在一个页面上处理多个表单。提交表单后,它就会被验证。我遇到的问题是,在插件中我可以查看表单的元素,但在 .submit 中我只能访问发送到 j!uery 的集合的最后一个表单。我的html有2种形式。 on 有一个名为 num 的输入,另一个有一个名为 alpha 的输入。他们都有自己的提交按钮。下面是 jQuery 插件的主要部分。对于插件,我只是发送它的形式。 o.attr 存储带有验证规则的属性名称。
var options = $.extend(defaults, options);
return this.each(function()
{
form=this;
var o = options;
//this gets me both inputs on page load
$('['+o.attr+']', form).each(function()
{
var val=$(this).val()
alert($(this).attr('name'))
})
//on submit It will alert the last forms input regardless of what form i submited
$(this).submit(function()
{
var o = options;
$('['+o.attr+']', form).each(function()
{
var val=$(this).val()
alert($(this).attr('name'))
})
return false;
})
});
I am writing my own form validation plugin. I am making to work with multiple forms on a page. when the form is submitted it is validated. The problem I am having is that in the plugin I can loo through the elements of the form but in the .submit I can only access the last form of the set sent to j!uery. my html is 2 forms. on has an input with a name of num and the other has one named alpha. they both have their own submit button. below is the main section of the jQuery plugin. for the plugin in am simply sending it form. o.attr is stores the name of the attribute with the validation rules.
var options = $.extend(defaults, options);
return this.each(function()
{
form=this;
var o = options;
//this gets me both inputs on page load
$('['+o.attr+']', form).each(function()
{
var val=$(this).val()
alert($(this).attr('name'))
})
//on submit It will alert the last forms input regardless of what form i submited
$(this).submit(function()
{
var o = options;
$('['+o.attr+']', form).each(function()
{
var val=$(this).val()
alert($(this).attr('name'))
})
return false;
})
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您忘记声明表单
var
,因此它是一个意外的全局变量,并且未按您的预期在闭包中捕获。因此,当调用
submit
函数时,form
将始终保存this
的最后一个值,无论提交的是哪个表单。(在代码上使用 lint 工具或支持 ECMAScript Fith Edition 严格模式的浏览器来检测意外的全局变量.)
You forgot to declare your form
var
, so it's an accidental global variable and not captured in a closure as you expected.Consequently by the time the
submit
function is calledform
will always hold the last value ofthis
regardless of which form was submitted.(Use a lint tool on your code, or an ECMAScript Fith Edition Strict Mode-supporting browser, to detect accidental globals.)
我觉得你把这件事想得太复杂了。像这样简单的事情会起作用吗?
I feel like you're making this too complicated on yourself. Would something as simple as this work?