Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

javascript - Add or subtract functions from onSubmit event handler?

I have the following code:

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;
}

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;

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Quirksmode has a wonderful article about advanced event registration.

Short form is: You can bind multiple events using addEventListener (attachEvent in older versions of IE).

if (someform.addEventListener) {
  someform.addEventListener('submit', somefunc, false);
} else {
  someform.attachEvent('onsubmit', somefunc);
}

To remove them you can use removeEventListener and detachEvent respectively.


Pretty quickly you'll get annoyed by repetitively typing addEventListener and attachEvent, and you might consider making some generic code to bind events for you. Fortunately, other programmers have had the same idea, and many libraries are available that handle event management elegantly. jQuery tends to be the library of choice, because binding an event is as simple as:

$('#formid').submit(somefunc);

the generic event binding method is:

$('#formid').on('submit', somefunc);

to unbind you can use:

$('#formid').off('submit', somefunc);

Although all of this is well documented in the jQuery API.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...