从onSubmit事件处理程序添加或减去函数? [英] add or subtract functions from onSubmit event handler?

查看:61
本文介绍了从onSubmit事件处理程序添加或减去函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

function showAddrBox() {
    var prompt = document.getElementById('addr_prompt');
    prompt.style.display = 'block';
    document.generic_form.address.style.display = 'block';
    document.generic_form.onsubmit = validateAddrForm;
}

function hideAddrBox() {
    var prompt = document.getElementById('addr_prompt');
    prompt.style.display = 'none';
    document.generic_form.address.style.display = 'none';
    document.generic_form.onsubmit = null;
}

问题是我有时会在onSubmit附加我想要的附加功能保留。我希望能够在onSubmit事件中添加和删除单个函数,而不只是使用onsubmit =设置它们。换句话说,我需要一种方法来完成这样的事情:

The problem is that sometimes I have additional functions attached to onSubmit that I want to preserve. I want to be able to add and remove individual functions from the onSubmit event, not just set them with "onsubmit =". In other words, I need a way to accomplish something like this:

document.form.onsubmit += function;
document.form.onsubmit -= function;

任何想法?

推荐答案

使用 element.addEventListener(eventName,callbackFunction,false) element.removeEventListener(eventName,callbackFunction)

其中eventName是没有'on'的处理程序的名称。所以onsubmit变成提交。

Where eventName is the name of the handler without the 'on'. So onsubmit becomes submit.

有关这两个函数的文档,请参阅:

For documentation of the two functions, see:

  • https://developer.mozilla.org/en/DOM/element.addEventListener
  • https://developer.mozilla.org/en/DOM/element.removeEventListener

这篇关于从onSubmit事件处理程序添加或减去函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆