日期:2014-05-17  浏览次数:20618 次

JQuery 动态删除添加html元素bind事件

JQuery 动态删除添加html元素,修改后的元素如果不bind事件,是不能有事件的,

?

下面是livequery插件的例子

?

?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery.js"></script>
		<script src="jquery.livequery.js" type="text/javascript" charset="utf-8"></script>
<title>jquery动态添加删除元素绑定事件</title>
<script  type="text/javascript" charset="utf-8">
$(document).ready(function(){
	$("#add").bind('click',function(){
		$('#example').empty().append('<li  ><a href="#" class="dynamic">动态修改html元素</a></li>');
		this.blur();
	});
	$(".dynamic").livequery('click',function(){
		alert("修改后的html元素的点击事件");
		return false;
	});
	
});
</script>
</head>
<body>
<div>
	<span><input type="button" name="add" value="add" id="add"></span>
		<ul id="example">
			<li  > <a href="#" class="dynamic">List Item</a></li>
			<li ><a href="#" class="dynamic">List Item</a></li>
		</ul>
</div>
</body>
</html>

?

当想通过页面元素ID或者CSS,当ID或者CSS不是页面原本的,是由后面动态添加或者是弹出窗口,都需要先绑定事件,然后才能对其进行操作,否则不行。

例如:

test是新增的id值,通过点击该id然后进行相关操作

?

$("#test").unbind('click');

$("#test").bind('click',function(){

   //对该id点击后的操作

});
?

?

?