简体   繁体   中英

HTML 5 data attributes not calling URL

I have created a button dynamically with the following code:

var del = $('<button/>')
     .addClass('btn btn-danger')
         .attr('data-type', 'DELETE')
         .attr('data-url', file.deleteUrl)
         .text('DELETE');

the file.deleteUrl is something like this: http://somedomain/?file=1411934997-1528.jpeg , which passes the data to be deleted to a processing script.

This (above) is providing the button with a data-url attribute, and when the button is clicked I'd like a DELETE call to be sent to that url.

However, its not working at the moment, and I dont know why.

in my console the button looks ok, but the call is not being fired when i click the button.

I'm a noob with data attributes and could use some help.

Thanks

It is not enough to just add data attributes. You need to attach an .on('click') event that should make an ajax call to the script. The script should return data showing whether it was successful or not.

Once you get success/failure results from the script that the URL calls, you should decide what to do with the element, whether you want to remove it or show an error message to the user.

ADDITIONAL INFO: If you'll be generating these buttons dynamically, then you'll need to attach the click event to each new on the you create.

You have to do the Ajax call on the button click:

del.click(function() {
    $.ajax({
        url: $(this).attr("data-url"),
        type: $(this).attr("data-type")
    });
});

You can also set this code for any btn-danger buttons:

$(document).on("click", ".btn-danger", function () {
    $.ajax({
        url: $(this).attr("data-url"),
        type: $(this).attr("data-type")
    }).done(function () {
        $(this).closest("tr").remove(); // to remove the complet row after delete success
    });
});

The advantage is that work for any dynamic futur btn-danger buttons (the event click bubble to the document ).

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