最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery `.parent().remove()` is not working - Stack Overflow

programmeradmin1浏览0评论

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();
});

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();
});
Share Improve this question edited May 29, 2017 at 20:49 Badacadabra 8,5357 gold badges31 silver badges54 bronze badges asked Jul 16, 2015 at 13:04 Destination DesignsDestination Designs 6831 gold badge5 silver badges17 bronze badges 2
  • Are your elements being added to the page dynamically? – j08691 Commented Jul 16, 2015 at 13:07
  • Please post your question with proper format, as this html string looks like html code. – Bhushan Kawadkar Commented Jul 16, 2015 at 13:13
Add a ment  | 

4 Answers 4

Reset to default 3

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/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.

发布评论

评论列表(0)

  1. 暂无评论