当前位置: 代码迷 >> JavaScript >> div的button的click会触发两次解决方案
  详细解决方案

div的button的click会触发两次解决方案

热度:20   发布时间:2012-05-15 14:35:29.0
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> 
  相关解决方案