jQuery动态添加元素后,为什么不能动态删除?

<html>
<head>
<meta charset="utf8">
<title>jquery动态添加的元素为何不能删除</title>

<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<style type="text/css">

.row{width:200px;height:500px;background: yellow;}
.one{width:200px;height:50px;background: green;}
</style>
</head>
<body>
<button id='add'>新增元素</button>
<div class="row">
<div class="one">
<span>删除</span>
</div>
<div class="one">
<span>删除</span>
</div>
</div>
</body>
<script type="text/javascript">

var str ="<div class='one' style='font-weight:bold;' >新添加的元素 <sapn>删除</span></div>";
$(document).ready(function(){
$("button").click(function(){
$(".row").append(str);
});
});

$('span').click(function(){
$(this).parent().remove();
})
</script>
</html>

首先,你的标签错了<sapn>删除</span>,应该是span,你写错了。

其次,动态加载的应该用绑定事件。根据你引入的jq库那就要用.on()事件。具体代码:

$("span").on("click",function(){
  $(this).parent().remove();
})追问

标签错了,对不起。但是你这个代码我放进去了,不行啊。点删除还没反应啊!???

追答$("span").on("click",function(){
  $(".one").remove();
})追问

我这边还是不行,你那边运行试了吗?

追答

大哥,能不能把这个放到$(function(){})里面?放到外面谁认识?

温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2018-03-04
<!DOCTYPE html>
<html>
  <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script class="jquery library" src="/js/sandbox/jquery/jquery-1.8.2.min.js" type="text/javascript"></script>
<title>
RunJS 演示代码
</title>
<style type="text/css">
.row{
width:200px;
height:500px;
background: yellow;
}
.one{
width:200px;
height:50px;
background: green;
}
</style>
<script type="text/javascript">
var str ="<div class='one' style='font-weight:bold;'><span>新添加的元素删除</span></div>";
$(document).ready(function(){
$("button").click(function(){
$(".row").append(str);
});
$(".row").delegate("span","click",function(){
$(this).closest("div").remove();  
});
});
</script>
  </head>
<body>
    <button id='add'>
新增元素
</button>
<div class="row">
<div class="one">
<span>
删除
</span>
</div>
<div class="one">
<span>
删除
</span>
</div>
</div>
  </body>
</html>

追问

为什么
$('span').click(function(){
$(this).parent().remove();
})
我这样写不行?啥原因?

本回答被提问者采纳
第2个回答  2016-02-03
jQuery动态添加元素后,可以动态删除的,不能删除是因为没有找到对应的节点。
举例如下:
//This prototype function allows you to remove even array from array
Array.prototype.remove = function(x) {
var i;
for(i in this){
if(this[i].toString() == x.toString()){
this.splice(i,1)
}
}
}
第3个回答  2015-03-31
后添加的元素是没有绑定click事件的.得重新绑定一下追问

怎么绑定?我不会写。。

追答

jQuery动态添加元素后,为什么不能动态删除?

jquery动态添加的元素为何不能删除

.row{width:200px;height:500px;background: yellow;}
.one{width:200px;height:50px;background: green;}

新增元素

删除

删除

var str ="新添加的元素 删除";
$(document).ready(function(){
$("button").click(function(){
$(".row").append(str);
$('span').click(function(){
$(this
});
});

$('span').click(function(){
$(this).parent().remove();
})

错了……手机编辑不方便,明天发给你吧

第4个回答  2015-03-31
不用remove()方法, 用detach()追问

我试了,代替掉remove不行。。

相似回答