简体   繁体   中英

How do I change the id set through an onclick function?

I have a delete modal set up, and the id of the module I want to be deleted is passed and set to the 'delete' button on the modal. The code below does this for me:

$(document).on("click", "#deleteModule", function () {

        var id = $(this).data('id');
        $("#deleteModuleButton").attr('data-id', id);

});

What this does is lets me click an 'X' by the module, and after I click that a modal drops down asking me if I'm sure. By clicking the XI pass the id to the modal, so that upon clicking 'I'm sure' it deletes the correct module by id.

Unfortunately it seems that the same id is passed every time I click the function. If I have ids 74, 75, and 76 on a page, I can delete the first one I click, say '74' - then every time I click 'X' on the other modules (75, 76), the initial value that was set from the first deletion (74) is never overwritten by the next element, so the other modules can't be deleted unless I refresh the page and try it again.

Is there something inherent on the onclick function that I'm overlooking, and is there a way to correct this?

If I am understanding your problem correctly, you can try to do something like:

$(document).on("click", "#deleteModule", function () {

    var id = this.data('id');

    showConfirmClosePrompt(id); // Re-factor to use across all modals

});

That way, you'll have the id no matter what modal id you click the X on. You may want to check to see if var id = $(this).data('id'); is your real problem too.

The answer to this was in the statement:

var id = $(this).data('id');

The better was to do this is:

var id = $(this).attr('data-id', id);

The former binds the same value, whereas the latter does not and can be reused. Changing this line in every repeated instance solved all of my problems!

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