Strange behavior with click event on button?

前端 未结 2 1440
灰色年华
灰色年华 2021-01-26 06:40

I am using jQuery File Upload plugin here for uploading files.

For each file that is added I generate a row in the table with a hidden button (that would be the single u

2条回答
  •  感情败类
    2021-01-26 07:19

    try this change this event binding

    $('button[name="singleUploadFile"]').click(function (){// Do Stuff}
    

    to

    $(document).on('click','button[name="singleUploadFile"]', function (){// Do stuff});
    

    What i think is the bug is, you are binding the events to buttons with [name="singleUploadFile"] to a click event, b ut the dom elements that are already in the page at page load gets binded to this event twice, thus on a single click the event gets triggered more than once.

    What you should do is

    Modify this code

    $('button[name="singleUploadFile"]').click(function () {
                    if (data.files.length > 0) {
                        data.submit();
                        addedFiles += 1;
                    }
                });
    
                $('button[name="removeFile"]').on("click", function () {
                    var fileToRemoveId = this.id;
                    if (fileToRemoveId == data.files[0].name) {
                        data.files.splice(0, 1);
                        $(this).closest('tr').remove();
                    }
                });
    

    so that all the events get binded to the document, so that only on event fire only one function gets executed.

提交回复
热议问题