开发者

jquery remove parent not working on dynamically created divs

im trying to use jquery in order to make a button remove its parent div.

my markup:

<div class="web_store_fields" id="web_store_input1">
<p>
<label for="web_store_address[]"  >Store Address : </label>        
<input name="web_store_address[]" class="web_store_info"  type="text" value="http://www." size="35"/>
<input class="button_remove_web_store" type="button" value="Remove"  />
</div>

jquery div removal code:

$('.button_remove_web_store').click(function() {
$(this).parents("div:first").remove();
});

this works ok for the div that's in the html when the page loads but not for div created dynamically by user (using this jquery code):

$('#button_add_web_store').click(function() {
var num = $('.web_store_fields').length;
var newNum  = new Number(num + 1);      
var newElem = $('#web_store_input' + num).clone().attr('id', 'web_store_input' + newNum);
$('#web_store_input' 开发者_JS百科+ num).after(newElem);
});

just to be clear, the dynamic creation is working fine, the problem is removing those divs.

any tips would be highly appreciated


Use a delegated handler (on) with the class as the selector so that any new buttons that get added later will still work.

$('body').on('click', '.button_remove_web_store', function() {
    $(this).parents("div:first").remove();
});


Do not use a live handler -- it has been deprecated in jQuery 1.7 and removed in jQuery 1.9 -- a breaking change for a great many people.

Instead, use the on handler, which is the recommended way now:

$(document).on('click', '.button_remove_web_store', function() {
    $(this).parents("div:first").remove();
});


I recently was running into an issue with $.on() that unclear and very similar to this application, as most "remove this's parent" functions are.

To illustrate with this question's example:

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

the big catch here is the second parameter. you must select the container $('.container') and pass the element selector of the 'button' as the second parameter to the .on function. so a definition(of sorts)

$('.container').on('click', '.myremovebutton', function(e){
    $(this).parent().remove();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜