简体   繁体   中英

jQuery `.parent().remove()` is not working

The solution may be obvious, but when clicking the .remove element, I am trying to remove the entire .tag element that is the parent. Currently, clicking the .remove element has no response.

HTML

'<div class="tag"><input id="' + id + '" type="hidden" name="' + name + '" value="' + value + '" />' + input + '<i class="remove dismiss fa fa-remove"></i></div>'

JS

$('.remove').on('click', '.remove', function() {
  $(this).parent().remove();
});

Try this : As you are adding remove link dynamically, you need to register click handler using .on() . But in your case you have error in using .on() . Please use below code.

$(document).on('click', '.remove', function() {
    $(this).parent().remove();
});

More Information on jQuery .on()

You can try this:

http://jsfiddle.net/myyzrwwe/

$('.remove').on('click', function() {
    $(this).parent().remove();
});

You shouldn't always use delegate the event to the same element that has been delegated. You need to select a static parent . In my example, the document object is the parent of everything.

$('body').on('click', '.remove', function() {
    $(this).parent().remove();
});

The problem might be you are binding the event to .remove, if this content is dynamic you might have a problem. Its better, in those cases, to bind to document.

$(document).on()

The callback has the event parameter, use that to remove.

function(e) {
  $(e.currentTarget).parent().remove();
}

Check if you undelegate elements.

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