JQuery callbacks fire too early

I am having a problem assigning functions to a button's click event in IE 7 using jQuery. Something like the following works great in Opera, but creates an infinite loop in IE:

function updateIndputFields(index, id) {
   $("#reloadBtn").click(function(){ updateIndputFields(index, id) });
}

      

As I understand it, an infinite loop would not be the expected behavior in this situation. But I am new to jQuery, so I might be missing something. Anyway, what do I need to do to get the click event for the reloadBtn button to be set to "updateIndputFields (index, id)" in IE?

0


source to share


3 answers


I think the key to your answer lies in canceling the event that you have already associated with the click event. I've used this in IE, and if I understand what you are trying to do, it seems to do what you need:

<script type="text/javascript">
function updateIndputFields(index, id) {
$('#output').append('<p>' + index + ' : ' + id + '</p>');
$('#reloadBtn').unbind('click');
$("#reloadBtn").click(function(){ updateIndputFields(index, id) });
}
</script>
<p><a href="#" id="reloadBtn">reload</a></p>
<p><a href="#" onclick="updateIndputFields(1,2);return false;">start</a></p>
<div id="output"></div>

      



Each click should output the passed parameters exactly once to the output div.

If you don't cancel the originally assigned click event, it remains present and every time it clicks, you attach a duplicate click event handler. Even in Firefox, not disabling the event creates an interesting recursive situation.

+6


source


or just use . one to bind the event



+1


source


Try to cancel the event before binding it.

0


source







All Articles