简体   繁体   English

如何使用Javascript的addEventListener()来覆盖HTML表单的默认submit()行为

[英]How to use Javascript's addEventListener() to override an HTML Form's default submit() behavior

How can I use addEventListener() to assign a handler to an HTML form's Submit button, similar to assignment to the button's 'onclick' attribute, without triggering the form's default submit() behavior? 如何使用addEventListener()为HTML表单的Submit按钮分配处理程序,类似于对按钮的'onclick'属性的赋值,而不触发表单的默认submit()行为?

I have no trouble assigning a custom function to the 'onclick' attribute of the "Submit" button. 我可以毫不费力地为“提交”按钮的“onclick”属性分配自定义功能。 The custom function executes a variety of steps, then creates an Ajax request object and uses this to send the data to the server. 自定义函数执行各种步骤,然后创建Ajax请求对象并使用它将数据发送到服务器。 The default submit() behavior isn't triggered. 不会触发默认的submit()行为。

submitButton.onclick = function() {
    mySubmit();
    return false;
};

function mySubmit() {
   //do stuff
   notTheDefaultUrl = generateNonStandardUrl();
   request = GetStandardAjaxRequestThingamabob();
   request.open("POST", notTheDefaultUrl, true);
   request.onreadystatechange = myHandler;
   request.send(formData);
   return false;
}

But with addEventListener(), the browser submit the request twice -- once under the Ajax request object, and again with the default HTML form submit() behavior. 但是使用addEventListener(),浏览器提交请求两次 - 一次在Ajax请求对象下,再次使用默认的HTML表单submit()行为。 (I can tell b/c the mySubmit function sends the data to a different URL than the default -- but both the default and the Ajax url are appearing in the server logs.) (我可以告诉b / c mySubmit函数将数据发送到与默认值不同的URL - 但默认和Ajax URL都出现在服务器日志中。)

var func = window['mySubmit'];
submitButton.addEventListener('click', func, false);

I'm aware that the function assigned to the button must return 'false' to prevent triggering the default submit() behavior. 我知道分配给按钮的函数必须返回'false'以防止触发默认的submit()行为。 I thought mySubmit() did that, and I've tried to write the function passed in via addEventListener to return false more explicitly (instead of 'func', 'function() {mySubmit(); return false}') but these dosn't work either. 我认为mySubmit()做到了这一点,并且我试图通过addEventListener编写传入的函数来更明确地返回false(而不是'func','function(){mySubmit(); return false}')但是这些dosn也没工作。

So how do I do this? 那我该怎么做?

UPDATE UPDATE

Comments to Peter's raised some browser compatability issues; 对Peter的评论提出了一些浏览器兼容性问题; also, IE doesn't support addEventListener(). 另外,IE不支持addEventListener()。 This code addresses these. 此代码解决了这些问题 I've tested it in Firefox and IE 8. 我在Firefox和IE 8中测试过它。

function func( event ) {
    if ( event.preventDefault ) { event.preventDefault()};  
    event.returnValue = false;  
    // do whatever
}

if (submitButton.addEventListener) {
    submitButton.addEventListener('click', func, false);
}
else {
    submitButton.attachEvent('onclick', func);
}

Apologies for the messy newbie formatting. 为凌乱的新手格式道歉。

You need to receive the event in your handler function, and prevent the event from executing its default behavior. 您需要在处理程序函数中接收事件,并阻止事件执行其默认行为。 This applies to click events, submit events - really any event that's cancelable. 这适用于click事件, submit事件 - 实际上任何可取消的事件。

// using your example
submitButton.addEventListener('click', func, false);

// here's what func should look like    
function func( event )
{
  if ( event.preventDefault ) event.preventDefault();
  event.returnValue = false;
  // do whatever
}

Shouldn't the handler be added as event listner for "submit" event? 不应该将处理程序添加为“提交”事件的事件列表器吗?

It makes sense the "click" event handler returning false does not prevent default submit behavior, I think. 我认为,返回false的“click”事件处理程序不会阻止默认提交行为。 It makes sense, kind of, that the form gets submitted to both targets. 将表单提交给两个目标是有道理的。

edit: added second paragraph. 编辑:添加第二段。

comment: And as Ken says the event listener should be added to the form and not the button. 评论:正如肯所说,事件监听器应该添加到表单而不是按钮。

edit 2: So I was wrong. 编辑2:所以我错了。 You shouldn't use "return false;" 你不应该使用“return false;” but something like... 但有点......

event.preventDefault ? event.preventDefault() : event.returnValue = false;

EASY WAY: Set the forms onsubmit attribute to return false 简单方法:将表单onsubmit属性设置为返回false

<form onsubmit="return false;">

Now if it MUST be done through assigning of an event listener through javascript, then the answer given by Peter Bailey is ideal. 现在,如果它必须通过javascript分配事件监听器来完成,那么Peter Bailey给出的答案是理想的。

My form validator does exactly what your trying to do. 我的表单验证器完全符合您的尝试。 Check out this example 看看这个例子

http://murdog05.github.com/yui3-gallery/examples/json/beforeSubmitExample.html http://murdog05.github.com/yui3-gallery/examples/json/beforeSubmitExample.html

And the code base 和代码库

http://yuilibrary.com/gallery/show/formvalidator http://yuilibrary.com/gallery/show/formvalidator

You might find it handy. 你可能会发现它很方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM