您的位置:首页 > 其它

DOM变化后事件绑定失效

2015-12-25 13:41 357 查看
前端经常要处理一些点击事件,或者是在用户保存时,做一些检查,这时,我们常常会绑定一些事件,如

click,change等。当然这都是我们经常使用的功能。

有些时候,我们的页面可能还会涉及到一些改变,譬如在点击某个按钮时,在页面中插入一些新的内容,如果此前

我们对这个内容绑定过事件,那么新插入的内容会不会绑定事件呢?很可惜,是没有,因为我们通常都是在页面加

载OK之后就绑定事件,而此时,这部分新内容还未插入到页面。如下:

<!doctype html>
<html lang="en">
	<head>
	<!--网站编码格式,UTF-8 国际编码,GBK或 gb2312 中文编码-->
		<meta http-equiv="content-type" content="text/html;charset=utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="Keywords" content="关键词一,关键词二">
		<meta name="Description" content="网站描述内容">
		<meta name="Author" content="Yvette Lau">
		<meta name = "viewport" content = " width = device-width, initial-scale = 1 ">		
		<title>CSSDemo</title>
		<!--css js 文件的引入-->
		<!-- <link rel="stylesheet" href="bootstrap-3.3.5-dist/css/bootstrap.min.css"/> -->
	</head>
	<body>
		<div id = "content">
			<input type="file" />
		</div>
		<div>
			<input type="button" value="点我">
		</div>
	</body>
	<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
</html>


当前的页面中除了一个file控件,还有一个button按钮。下面是JS的内容,在JS中我们为file控件绑定了change事件,

在点击button按钮时,我们会往页面中插入一个file控件。

<script type="text/javascript">
	
	$(function(){
		$('input[type ="file"]').change(function(){
			console.log($(this).val() )
			if($(this).val() == ""){
				alert("你好")
			}
		})	

		$('input[type ="button"]').click(function(){
			$("#content").append('<input type="file"/>')
		})
	})

</script>


通过测试,可以发现,第一个file在change时,是能够触发事件的,而第二插入的file则没有change事件。对于这个问

题,有如下两种解决方法:

第一种是将绑定change事件封装成一个函数,在点击button按钮插入file控件之后,调用这个函数。如下:

<script type="text/javascript">	
	$(function(){
		function fileChange(){
			$('input[type ="file"]').change(function(){
				console.log($(this).val())
				if($(this).val() == ""){
					alert("你好")
				}
			})
		}
		fileChange();
		$('input[type ="button"]').click(function(){
			$("#content").append('<input type="file"/>');
			fileChange();
		})
	})
</script>


另一种方式,是在DOM加载之后和DOM内容发生改变时,绑定file控件的change事件,如下:

<script type="text/javascript">
	
	window.onload,window.onchange = function(){
		$('input[type ="file"]').change(function(){
			console.log($(this).val() )
			if($(this).val() == ""){
				alert("你好")
			}
		})
	}
	
	$('input[type ="button"]').click(function(){
		$("#content").append('<input type="file"/>')
	})
	
</script>
两种方式均能解决此问题,至于究竟使用何种方式,就看个人的喜好。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: