标签:javascript
javaSciprt事件中有两个很重要的特性:事件冒泡以及目标元素。以下程序模拟一下事件冒泡:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>index</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script type="text/javascript"> function fun1(){ console.log("fun1 call!!"); } function fun2(event){ console.log("fun2 call!!"); } </script> </head> <body> <label onclick="fun2(event)"> radio : <input type="radio" onclick="fun1()"/> </label> </body> </html>
可以看到点击label后事件触发的顺序:
1.触发label的onclick事件;
2.触发input的onclick事件;
3.input的点击事件引起事件冒泡触发外层的label点击事件。
解决办法:
如果点击了某个元素不想让事件继续传播可以使用以下方式
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>index</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script type="text/javascript"> function fun1(){ console.log("fun1 call!!"); } function fun2(event){ console.log("fun2 call!!"); stopDefault(event); } function stopDefault(e) { //如果提供了事件对象,则这是一个非IE浏览器 if(e && e.preventDefault) { //阻止默认浏览器动作(W3C) e.preventDefault(); } else { //IE中阻止函数器默认动作的方式 window.event.returnValue = false; } return false; } </script> </head> <body> <label onclick="fun2(event)"> radio : <input type="radio" onclick="fun1()"/> </label> </body> </html>这样只会调用label的点击事件,并且只调用一次。
标签:javascript
原文地址:http://blog.csdn.net/liuchangqing123/article/details/43950261