Strange behavior with click event on button?

前端 未结 2 1415
灰色年华
灰色年华 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:07

    The following code binds the event to all buttons with the name "singleUploadFile".

    $('button[name="singleUploadFile"]').click(function () {
       if (data.files.length > 0) {
           data.submit();
           addedFiles += 1;
       }
    });
    

    But you want it to bind the event just to the newly added button (not to buttons that already have it bound).

    Do the following:

    data.context.find('button[name="singleUploadFile"]').click(function () {
       if (data.files.length > 0) {
           data.submit();
           addedFiles += 1;
       }
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题