在label中包裹input,同时给label添加点击事件,会发现事件执行两次

问题:在label中包裹input,同时给label添加点击事件,会发现事件执行两次;
原因:input的时间冒泡

解决方法:

html

<label id="lab">
	<input type="checkbox" name="" id="che" value="" checked="true"/>check1
</label>

方法一:将事件绑定到input标签上,去掉label标签上的事件绑定;

$("#che").on("click",function(event){
	console.log(1)
});

方法二:给input标签阻止事件冒泡,同时将事件绑定到label标签上

$("#lab").on("click",function(){
	console.log(1)
});
$("#che").on("click",function(event){
	event.stopPropagation();//阻止其继续冒泡
});

猜你喜欢

转载自blog.csdn.net/hangGe0111/article/details/81703671