Event Propagation and Multiple Event Handlers
Okay, I'm confused. I've got a global click event handler on document
. On the page I have a few links. Each link is handled by the same click event handler that, among other things, prevents the event from bubbling to the document level and prevents the link from executing. Of these links, one has a specific click handler that is supposed to do its thing and then pass off the event to the generic click event for the links. But it's not.
document.onclick = function()
{
document.body.innerHTML += "You clicked me!";
};
document.getElementsByTagName("a")[0].onclick = function(e) {
this.innerHTML += " Click it!";
e.stopPropagation();
//This return false appears only to
//prevent the link from开发者_开发百科 its default action
return false;
};
document.getElementById("link").onclick = function(e) {
this.innerHTML += " Go ahead, ";
//But this return false appears to stop
//the propagation up to the previous event
//I would think that removing the link below
//would cause the event to propagate to the event
//above which would then stop the propagation and
//prevent the default, but apparently this is
//not the case; removing the line below causes
//the link to load Google like normal
return false;
};
How do I get the lower event to fire and up to the upper event which then cancels the event?
See what I mean here
Ha, duh. using element.on<event>
is simply setting the property in the DOM for the element, which means each event can only have one handler. Instead, I need to use addEventListener
combined with a proper use of event.preventDefault()
and event.stopPropagation()
In my first attempts, I was putting what I wanted to be the first handler second, but that really meant it was overriding the first. In this case, I need to put the handler I want first first, since the handler is being attached to the event.
My revised code should be:
document.onclick = function()
{
document.body.innerHTML += "You clicked me!";
};
document.getElementById("link").addEventListener("click",function() {
this.innerHTML += " Go ahead, ";
});
document.getElementsByTagName("a")[0].addEventListener("click",function(e) {
this.innerHTML += " Click it!";
e.stopPropagation();
e.preventDefault();
});
http://jsbin.com/ecozep/8/edit
精彩评论