Edit based on updated question:
The issue is that you're calling $.ajaxComplete()
in your callback. You should get rid of that. The anonymous callback function is all you need.
The purpose of $.ajaxComplete()
is to setup a default function to run when any ajax request completes. If this is what you want, you should take it out of the current callback, and just place it in the .ready()
call so that it only runs once.
The way you're doing it right now, for each click (and successful response) you're adding another identical handler. So after you click 5 times, it now has 5 of the same click handler.
From the docs: http://api.jquery.com/ajaxComplete/
Whenever an Ajax request completes, jQuery triggers the ajaxComplete event. Any and all handlers that have been registered with the .ajaxComplete() method are executed at this time.
Original answer
This must not be your actual code, because it won't run at all the way you have it.
You don't have a function
declaration for your function. You need to initialize i
with a value like 0
, and your closing parenthesis for the click
handler is misplaced.
That said, your code works fine for me when corrected.
Try it out: http://jsfiddle.net/sGWjL/1/
If the alert pops up 5 times for you, then you need to paste more (or actual) code being used.
var i = 0;
var k = 5;
$('document').ready(function () {
$('#someElement').click(function (e) {
e.stopImmediatePropagation();
i++;
if (i >= k) {
my_function();
}
});
});
function my_function() {
alert(i);
$('#myDisplay').text("You have clicked on '#someElement' " + i + "times");
}