Michael Michael - 3 months ago 9
jQuery Question

Click event handler is called n-1 times the click number

On the page there is a list of dates. To the right of each date are two icons: update and delete. I want to catch the data-update_url, and data-delete_url.

The problem is that when I click on, say, update icon, nothing happens.
Another click makes it show alert message. Another click makes shows alert message twice. And so on. That is alert message is shown n-1 clicks number.

I tried to model it at jsfiddle. But failed.

Well, could you suggest what may be the reason of such behaviour?

<li>03 January 2016
<a class="update" id="update_framedate_26" href="javascript:void(0)"><span data-update_url="/frame_date/26/update/" class="glyphicon glyphicon-edit" aria-hidden="true"></span></a>
<a class="delete" id="remove_framedate_26" href="javascript:void(0)"><span data-delete_url="/frame_date/26/delete/" class="glyphicon glyphicon-remove" aria-hidden="true"></span></a>
</li>


<li>15 January 2015
<a class="update" id="update_framedate_27" href="javascript:void(0)"><span data-update_url="/frame_date/27/update/" class="glyphicon glyphicon-edit" aria-hidden="true"></span></a>
<a class="delete" id="remove_framedate_27" href="javascript:void(0)"><span data-delete_url="/frame_date/27/delete/" class="glyphicon glyphicon-remove" aria-hidden="true"></span></a>
</li>



<script>
function get_form(url){
var update_url = url.target.getAttribute('data-update_url');
var delete_url = url.target.getAttribute('data-delete_url');

var cuaghtUrl = update_url || delete_url;

alert(cuaghtUrl);
}

function handle_update_buttons(){
var update_button_list = $(".update");
$(update_button_list).click(function() {
$(this).click(get_form);
})
}

function handle_update_buttons(){
var update_button_list = $(".update");
$(update_button_list).click(function() {
$(this).click(get_form);
})
}

function handle_delete_buttons(){
var delete_button_list = $(".delete");
$(delete_button_list).click(function() {
$(this).click(get_form);
});
}

handle_update_buttons();
handle_delete_buttons();
</script>

Answer

This code hooks up a click handler that, every time it's called, will hook up a click handler calling get_form:

function handle_update_buttons(){
    var update_button_list = $(".update");
    // ------------------vvvvvv
    $(update_button_list).click(function() {
        $(this).click(get_form);
    // --------^^^^^^
    })
}

Note the arrows in the comments. So the first time, it just hooks up the second handler and that's all. The second time, it hooks up a handler again and then the handler from the first call is fired. The thrid time, it hooks up a handler for the third time, and the first two handlers are triggered. And so on.

You probably meant to do this:

function handle_update_buttons(){
    $(".update").click(get_form);
}

...which just hooks up a handler once, which will call get_form on each click.