日期:2014-05-16  浏览次数:20353 次

div的button的click会触发两次
HTML code
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">     <title>     </title>     <script type="text/javascript">         function SayHello() {             alert("Hello World");         }     </script> </head> <body>     <form id="form1" runat="server">     <div onclick="SayHello()" style="width:300px; height:300px; background-color:Green">     <input type="button" value="click me" onclick="SayHello()" />     </div>     </form> </body> </html> 


如果我们点击button,则会弹出两次Hello World,因为,button实际上是在div内,我们点击button的时候同时也在点击div。所以同时会触发button的onclick事件,也会触发div的onclick事件
请问大侠 怎么解决这个问题

------解决方案--------------------
HTML code


<html xmlns="http://www.w3.org/1999/xhtml">
    
    <head runat="server">
        <title>
        </title>
        <script type="text/javascript">
            function SayHello(e) {
                alert("Hello World");
                e = window.event || e;
                if (e.stopPropagation) {
                    e.stopPropagation();
                } else {
                    e.cancelBubble = true;
                }
            }
        </script>
    </head>
    
    <body>
        <form id="form1" runat="server">
            <div onclick="SayHello(event)" style="width:300px; height:300px; background-color:Green">
                <input type="button" value="click me" onclick="SayHello(event)" />
            </div>
        </form>
    </body>

</html>