简体   繁体   中英

Passing the correct context to a function with arguments from ready function

I have spent a day trying to find the way to pass the correct context to the removeForm . The goal is to use the removeForm which is called when pressing <a class="remove_2"> remove </a> link to remove the content of the class passed to removeForm in this case "subform2". Here is what I tried:

function removeForm(tgsubf) {
    var $removedForm = $(this).closest(tgsubf);
    var removedIndex = parseInt($removedForm.data('index'));
    $removedForm.remove();
}
    
$(document).ready(function() {
    $('.remove_2').click(function(e){
        e.preventDefault();
        removeForm('.subform2')
    });
}
<div class="subform2">
    <a class="remove_2"> remove </a>
</div>

I know that the context depends on how I call the function but also if I call the function using removeForm('subform2') I still have this problem. The full example is hosted here .

If you want to remove the .subform2 element that contains the .remove_2 which was clicked, you can do the following.

When your are inside an event callback you pass to jQuery, this (generally) holds the element that received the event. So you should change your code to have the following:

$('.remove_2').click(function(e){
    e.preventDefault();
    removeForm(this)  // <-- 'this' will refer to $('.remove_2')
});

Then you can change your removeForm() to get the immediate ancestor of the element passed to it (which would be .remove_2 ) that has .subform2 for class and remove it, like this:

function removeForm(anchor) {
    var $removedForm = $(anchor).closest('.subform2');
    $removedForm.remove();
}

UPDATE

You should be able to pass a selector to removeForm to identify the ancestor, like this:

function removeForm(el, ancestorSelector) {
    // Do check to ensure ancestorSelector is provided, before using it.
    var $removedForm = $(el).closest(ancestorSelector);
    $removedForm.remove();
}

You can update how you call it like this:

$('.remove_2').click(function(e){
    e.preventDefault();
    removeForm(this, '.subform2')  // <-- 'this' will refer to $('.remove_2')
});

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