我试图使用jquery来使按钮删除其父div。
我的加价:
<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删除代码:
$('.button_remove_web_store').click(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).clone().attr('id', 'web_store_input' + newNum);
$('#web_store_input' + num).after(newElem);
});
为了清楚起见,动态创建工作正常,问题是删除那些div。
任何提示都将受到高度赞赏
答案 0 :(得分:17)
使用委派的处理程序(on)将该类作为选择器,以便稍后添加的任何新按钮仍然有用。
$('body').on('click', '.button_remove_web_store', function() {
$(this).parents("div:first").remove();
});
答案 1 :(得分:3)
不要使用live处理程序 - 它已在jQuery 1.7中弃用,在jQuery 1.9中删除 - 对于很多人来说是一个重大改变人。
相反,请使用on处理程序,这是现在推荐的方法:
$(document).on('click', '.button_remove_web_store', function() {
$(this).parents("div:first").remove();
});
答案 2 :(得分:0)
我最近遇到的$.on()问题与此应用程序不一致且非常相似,因为大多数“删除此父级”功能都是。
用这个问题的例子说明:
$('.web_store_fields').on('click', '.button_remove_web_store', function(e){
$(this).parent().remove();
});
这里的大问题是第二个参数。您必须选择容器$('.container')
并将“按钮”的元素选择器作为第二个参数传递给.on
函数。所以定义(各种)
$('.container').on('click', '.myremovebutton', function(e){
$(this).parent().remove();
});