Event bubbling for parent of <a>, which returns false from onclick event listener
I try to make a common solution for the following task: onclick
event listener for element
<a href="#">Some text</a>
must return false. It can stop page scrolling after click.
$("a[href='#']").bind("click", function () { return false; });
It can stop sc开发者_如何学Pythonrolling but return false
stop bubbling too! So, if I have the following code:
HTML
<div class="clickable">
<a href="#">Text</a>
</div>
Javascript (JQuery)
$("a[href='#']").bind("click", function () { return false; });
$(".clickable").bind("click", function(){alert("It works!");})
and if I click on "Text", there is no alert.
Can I restore bubbling? Or, may be, there is any another common way to return false from onclick
event listener of every such "a" tag? Or the only way is to add listener function(){alert("It works!");}
on "a"?
Change your click function's signature to accept the event args and use preventDefault
:
$("a[href='#']").bind("click", function (e) { e.preventDefault(); });
$(".clickable").bind("click", function(){alert("It works!");})
Here's a working fiddle.
<a href="#" onclick="return false;">Some text</a>
Your jQuery-bound click functions should keep working.
Example:
http://jsfiddle.net/mU2dq/1/
To stop something from bubbling I always follow this:
$('myAnchor').live("click", function(e) {
e.preventDefault();
e.stopPropagation();
//or if you want to stop all handlers
e.stopImmediatePropagation();
//code here
//for IE etc.
return false;
});
精彩评论