jquery remove parent不工作在动态创建的div [英] jquery remove parent not working on dynamically created divs

查看:93
本文介绍了jquery remove parent不工作在动态创建的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用jquery以使按钮删除其父div。



我的标记:

 < div class =web_store_fieldsid =web_store_input1> 
< p>
< label for =web_store_address []>商店地址:< / label>
< input name =web_store_address []class =web_store_infotype =textvalue =http:// www。大小= 35/>
< input class =button_remove_web_storetype =buttonvalue =删除/>
< / div>

jquery div删除代码:



<$ p $点击(function(){
$(this).parents(div:first)。remove();
}) ;

这个工作对于html中的div,当页面加载但不是
由用户动态创建的div(使用此jQuery代码):

  $('#button_add_web_store')click(function() 
var num = $('。web_store_fields')。length;
var newNum = new Number(num + 1);
var newElem = $('#web_store_input'+ num) ().attr('id','web_store_input'+ newNum);
$('#web_store_input'+ num).after(newElem);
});

只是要清楚,动态创建工作正常,问题是删除这些div。 p>

任何提示将被高度赞赏

解决方案

使用委托处理程序(<一个href =http://api.jquery.com/on/ =nofollow noreferrer> on ),该类作为选择器,以便稍后添加的任何新按钮仍然可以工作。 / p>

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


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

这篇关于jquery remove parent不工作在动态创建的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆