views:

35

answers:

2

When I'm loading some content through ajax it returns an jQuery .click event and some elements. But when the ajax content is loaded a couple of times and I click the the button that is bound to the .click event, the action is executed a couple of times.

For example the ajax content is:

<script type="text/javascript">
$('#click').click(function() { alert('test') });
</script>
<input type="button" id="click" value="click here">

If this is refreshed 5 times and I click the button I will get 5 alert boxes.

Is there a workaround for this?

A: 

You can use the unbind function just before the click, something like this:

$('#click').unbind('click').click(function() { alert('test') });

That should let only one function associated with the click

willvv
Thank you willvv, that did the job :)
Jens
A: 

The JQuery one method unbinds the handler after it is invoked:

$('#click').one("click",function() { alert('test') });

More info: http://docs.jquery.com/Events/one

brian chandley