单击jquery是否未删除Div?
这项工作单击jquery是否未删除Div?,jquery,Jquery,这项工作 测试 $('.test2')。单击(函数(){ $('.test2').remove(); 这个-不工作 <div class="test">test</div> $('.test').click(function(){ $('body').prepend('<div class="test2"></div>'); }); $('.test2').click(function(){ $('.test2').remove(); });
测试
$('.test2')。单击(函数(){
$('.test2').remove();
这个-不工作
<div class="test">test</div>
$('.test').click(function(){
$('body').prepend('<div class="test2"></div>');
});
$('.test2').click(function(){
$('.test2').remove();
});
测试
$('.test')。单击(函数(){
$('body')。前缀(“”);
});
$('.test2')。单击(函数(){
$('.test2').remove();
});
为什么?试试:
$(document).on('click','.test2',function(){
$('.test2').remove();
});
您需要使用事件委派,因为它是动态创建的
$(document).on("click",".test2",function(){
$(this).remove(); //you can use 'this' instead
});
写:
$('.test')。单击(函数(){
$('body')。前缀(“”);
$('.test2')。单击(函数(){
$('.test2').remove();
});
});
或
$('.test')。单击(函数(){
$('body')。前缀(“”);
});
$(文档).on('单击','.test2',函数(){
$('.test2').remove();
});
使用live click,它工作正常。请参阅fiddle更新
$('.test')。单击(函数(){
$('body')。前缀(“”);
});
$('.test2').live('click',function(){
$('.test2').remove();
});
原因:为什么上面的代码有效而你的代码无效
1.您正在动态添加元素。简单地说,加载DOM时,您添加的元素不存在
2.您需要为将来添加的任何元素分配。我们通常使用的方法,如。单击(…),.on(…)
等,仅适用于DOM中当前的元素
3.这是您提供活动委派的方式
$(document).on('keyup', '.class', function(){.........})
@Ap313请参阅文件
$('.test').click(function(){
$('body').prepend('<div class="test2"></div>');
$('.test2').click(function(){
$('.test2').remove();
});
});
$('.test').click(function () {
$('body').prepend('<div class="test2"></div>');
});
$(document).on('click','.test2',function () {
$('.test2').remove();
});
$('.test').click(function(){
$('body').prepend('<div class="test2"></div>');
});
$('.test2').live('click',function(){
$('.test2').remove();
});
$(document).on('click','.test2',function(){
$('.test2').remove();
});
$(document).on('keyup', '.class', function(){.........})