简体   繁体   中英

Passing a parameter into the JQuery.slideUp() callback

I'm trying to slide my element up, then delete it. However I can't seem to pass the element ID into the callback that deletes it.

I can't hardcode the value since this has to be dynamic.

insertedTemplates is a collection of templates that are inserted into the page. When the user changed his/her option, a new element is inserted and the old one deleted.

The following will fail to delete the element because it is undefined:

    var elementId = insertedTemplates[i].id;
    $('#'+elementId).slideUp(400, function(elementId) {
        $('#'+elementId).remove();
    });

I found a post that suggests just passing the value in by adding it right after the function declaration.

This will immediately delete the element:

    var elementId = insertedTemplates[i].id;
    $('#'+elementId).slideUp(400, function() {
        $('#'+elementId).remove();
    }(elementId));

You don't need to pass the element id. Use $(this) inside the callback.

var elementId = insertedTemplates[i].id;
$('#' + elementId).slideUp(400, function (elementId) {
    $(this).remove(); // <---- Use $(this)
});

$(this) inside the slideUp callback is the element on which the function is called.

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