简体   繁体   中英

jquery function is being called more than once on single click

I am having more than one button with same class name and different id. but when I click on button, it's called for more than one everytime. for information about code in action, please see the video : https://nimb.ws/3RMoNP

Here is my code

$(document).on("click", ".delete_attachment_confirmation", function(e){
    e.preventDefault();

    var attachment_id = $(this).data('attachmentid');
    $('#delete_attachment_confirmation_'+attachment_id).attr("disabled", true);
    $('#delete_attachment_confirmation_'+attachment_id).text("Deleting file");


    $.ajax({
      url: "<?php echo base_url('attachment/delete_attachment/')?>"+$(this).data('attachmentid'),
      type: "GET",  
      dataType: "text",
      success: function(data){

        $("#row_"+attachment_id).remove();

        $("#attachment_message_body").text(data);

        $('#delete_attachment_'+attachment_id).modal('hide');

        // attachment message
        $('#attachment_message').modal('show');

        // modal issue removal trick
        $('.modal-backdrop').removeClass('modal-backdrop');

      }
    }); 
});


<button class="btn btn-danger delete_attachment_confirmation" id="delete_attachment_confirmation_<?=$row->id?>" data-attachmentid="<?=$row->id?>" ><?php echo $this->lang->line('btn_modal_delete');?>

updated button code

<button class="btn btn-danger delete_attachment_confirmation" id="delete_attachment_confirmation_<?=$row->id?>" data-attachmentid="<?=$row->id?>" ><?php echo $this->lang->line('btn_modal_delete');?>

Highlighted part is showing us that ajax function is being called more than once.

在此处输入图片说明

There is nothing in above JS code that is causing it run twice, just that button does not have closing tag and multiple buttons without closing tags and having same class may be the reason, i just ran your code in codepan and it is running fine.

<button class="btn btn-danger delete_attachment_confirmation" id="delete_attachment_confirmation_<?=$row->id?>" data-attachmentid="<?=$row->id?>" ><?php echo $this->lang->line('btn_modal_delete');?></button>

https://codepen.io/balramsinghindia/pen/OJLzjbo

I have used solution provided in this question.

Ajax, prevent multiple request on click

  $(".classNamw").unbind().click(function() {
//Your stuff
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM