views:

940

answers:

3

I have a problem when assigning functions to the click event of a button in IE 7 with jQuery. Something like the following works fine in Opera but produces 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'm new to jQuery so maybe I've missed something. Anyways, what should I do to make the click event of the reloadBtn button be set to 'updateIndputFields(index, id)' in IE?

A: 

Try unbinding the event before binding it.

strager
+5  A: 

I think the key to your answer is in unbinding the event that you have already bound to the click event. I used this on IE and, if I understand what you're 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 into the output div.

If you don't unbind the originally assigned click event, then it stays present and you attach a duplicate click event handler to the event each time it's clicked. Even in Firefox, not unbinding the event creates an interesting recursive situation.

ringmaster
This is what I assumed with my answer: that the callbacks were accumulating.
strager
+1  A: 

or just use .one to bind the event

redsquare