这link1 - 工作
<div class="test">test</div>
<div class="test2"></div>
$('.test2').click(function(){
$('.test2').remove();
这link2 - 不工作
<div class="test">test</div>
$('.test').click(function(){
$('body').prepend('<div class="test2"></div>');
});
$('.test2').click(function(){
$('.test2').remove();
});
为什么?
答案 0 :(得分:3)
答案 1 :(得分:3)
您需要使用事件委派,因为它是动态创建的
$(document).on("click",".test2",function(){
$(this).remove(); //you can use 'this' instead
});
答案 2 :(得分:2)
写:
$('.test').click(function(){
$('body').prepend('<div class="test2"></div>');
$('.test2').click(function(){
$('.test2').remove();
});
});
OR
$('.test').click(function () {
$('body').prepend('<div class="test2"></div>');
});
$(document).on('click','.test2',function () {
$('.test2').remove();
});
答案 3 :(得分:2)
使用实时点击,它工作正常。请参阅小提琴更新
$('.test').click(function(){
$('body').prepend('<div class="test2"></div>');
});
$('.test2').live('click',function(){
$('.test2').remove();
});
答案 4 :(得分:2)
$(document).on('click','.test2',function(){
$('.test2').remove();
});
原因:为什么上面的代码有效而你的代码没有?
1.您正在动态添加元素。简单来说,加载DOM时,您附加的元素不存在。
2.您需要为将来添加的元素分配Event Delegation。我们通常使用的方法如.click(...) , .on(..)
等仅适用于当前在DOM中的元素。
3.这就是你提供活动授权的方式。
$(document).on('keyup', '.class', function(){.........})