I have event handler bound to every element of the page via $(document).bind().
Does anybody know how to unbind this handler for particular element?
Here is my sample code that doesn't work the way I want:
<html><head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"> </script>
</head>
<body>
<div id="mid" style="cursor:pointer" >click me</div>
<div>sample</div>
<script type="text/javascript">
var fun = function() {
alert('default handler');
};
$(document).bind('click.custom', fun);
//trying to unbind the handler but it remains there
$("#mid").unbind('click.custom');
</script>
</body>
</html>
Considering Daniel's answer here is this problem again:
var ff = function() {
alert('additional');
}
$(document).bind('click.custom', fun);
$(document).bind('click.custom2', ff);
$("#mid").bind('click.custom', false);
here fun event handler was perfectly unbound from #mid element, but ff event handler was unbound also 开发者_如何学Pythonand that is a problem for me.
Its called event bubbling. The events of the nested elements go up to the parents.
You should bind
to #mid
and return false
from that handler.
There is only a single event bound to the document. Because of bubbling, the event will be sent up the DOM hierarchy until its propagation is stopped, or it reaches the document.
You could either modify the callback to ignore this event if it came from #mid
, or use the in-built delegate/live to achieve the same effect.
$(document).delegate('[id!="mid"]', 'click.custom', fun);
This will ignore events coming from an element having the id "mid". Another alternate is to modify the function itself.
function fun() {
if (this.id == "mid") {
return; // if event came from #mid, ignore it.
}
// continue processing as normal
}
精彩评论