IE and jquery event binding
I’ve run into a little bit of an annoyance whilst trying to rebind a click event on an element during a click event on the same element.
Basically a user clicks an element, some code runs and then the c开发者_如何转开发lick event for that element is change to point to another function.
Now in every browser apart from IE this works fine.
However in IE the new function that the elements click event is being pointed to is fired when it’s being bound and I can’t for the life of my figure out why.
Any ideas? Code below:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.js'></script>
<script type='text/javascript'>
function setUpBind()
{
$("#foo").removeAttr("onclick");
$("#foo").bind("click", function() {newBindFunction()});
alert('First bind function');
}
function newBindFunction()
{
alert('This is the new bind function.');
}
</script>
</head>
<body>
<span id="foo" onclick="setUpBind()">Button 1</span>
</body>
</html>
Do it all from jquery! http://jsfiddle.net/gNvQg/3/
$(function() {
function firstHandler() {
$('#foo').unbind('click', firstHandler);
$('#foo').click(secondHandler);
alert('First Handler');
}
function secondHandler() {
alert('Second Handler');
}
$('#foo').click(firstHandler);
})
Here's a jsfiddle that works without jquery, since you seem to want to attach them through the HTML http://jsfiddle.net/gNvQg/2/
I think the lesson learned is "Don't mix both property/attribute style handlers with events added through addEventListener/attachListener". I observed that IE's bug only happens when you are setting an handler through jquery and it's been previously attached with a property (attribute) handler
精彩评论