多种表单的多个 onsubmit 处理程序
我正在编写一段附加的 JavaScript,旨在在提交表单时捕获信息。我需要适应网页上可能有多个表单的情况,其中没有/部分/全部可能已经定义了 onsubmit 处理程序......并且我需要在调用螺栓代码后触发原始处理程序。
我有一个包含 2 个表单的测试用例设置,第一个没有 onsubmit 处理程序,第二个是一个简单的警报框。
我尝试了下面的代码 - 但这似乎将预先存在的处理程序从 form2 复制到 form1:
window.onload=pageinit;
function pageinit()
{
for (var x=0; x < document.forms.length; x++) {
var origSubmit=document.forms[x].onsubmit;
if (typeof origSubmit != 'function') {
document.forms[x].onsubmit=dosubmit;
} else {
document.forms[x].onsubmit = function (event) {
dosubmit(event);
return origSubmit(event);
}
}
}
}
function dosubmit(ev)
{
alert('bolt-on invoked from ' + ev.target.name);
}
有什么想法吗?
TIA
I'm writing a bolt-on bit of javascript which is intended to capture information when a form is submitted. I need to accomodate the scenario where there may be multiple forms on a web page, none/some/all of which may already have onsubmit handlers defined....and I need to fire the original handler after calling the bolt-on code.
I've got a test case setup with 2 forms, the first has no onsubmit handler, the second a simple alertbox.
I tried the code below - but that seemed to copy the pre-existing handler from form2 into form1:
window.onload=pageinit;
function pageinit()
{
for (var x=0; x < document.forms.length; x++) {
var origSubmit=document.forms[x].onsubmit;
if (typeof origSubmit != 'function') {
document.forms[x].onsubmit=dosubmit;
} else {
document.forms[x].onsubmit = function (event) {
dosubmit(event);
return origSubmit(event);
}
}
}
}
function dosubmit(ev)
{
alert('bolt-on invoked from ' + ev.target.name);
}
Any ideas?
TIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我真的不明白你想要做什么,但你有典型的循环定义中的函数问题:
在任何
document.forms[x].onsubmit
函数被调用(显然是在循环完成之后),每个处理程序中的origSubmit
将指向相同的函数(document.forms[document.forms.length - 1].onsubmit
)。您必须“捕获”origSubmit
的值,因为 JavaScript 只有函数作用域,没有块作用域:另请参阅 傻瓜式闭包,示例 5
I don't really get what you want to do, but you have the typical function in loop definition problem:
At the the time when any
document.forms[x].onsubmit
function is called (obviously after the loop finished),origSubmit
in each handler will point to the same function (document.forms[document.forms.length - 1].onsubmit
). You have to "capture" the value oforigSubmit
because JavaScript has only function scope, not block scope:See also Closures for Dummies, Example 5
我认为问题可能是您的
origSubmit
变量;它对您在那里创建的函数是“封闭的”,但它被 for 循环更改了。尝试:
I think the issue may be your
origSubmit
variable; it is 'closed' over the function you create there but it's changed by the for loop.Try: