使用javascript模拟o​​nclick事件 [英] simulating onclick event with javascript

查看:407
本文介绍了使用javascript模拟o​​nclick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是在div中放置一个比按钮本身更宽的图像按钮,当点击外部div时,我想调用图像按钮onclick()函数。我期望从下面的HTML代码,当我点击按钮本身,它应该只提醒按钮点击。当我点击外面的div,它应该提醒div点击,然后按钮点击。问题是,当我点击div,它警告:div点击,然后按钮点击,然后div点击再次,按顺序。当我点击按钮,它提醒:按钮点击,然后div点击,然后按钮点击,然后div点击。



我缺少这里,有什么帮助吗?

 < html> 
< body>
< div style =width:200px; border:1px solid red; onclick =alert('div clicked');(document.getElementById('addButton'))。click();>
< input type =buttononclick =alert('button clicked');
id =addButton/>
< / div>
< / body>
< / html>


解决方案

你错过的是,冒泡文档树触发父元素的所有点击处理程序。要停止它,请在事件对象上调用stopPropagation。

 < input type =buttononclick =event.stopPropagation? event.stopPropagation():(event.cancelBubble = true); alert('button clicked'); 
id =addButton/>

(在旧IE中没有stopPropagation,需要设置event.cancelBubble = true) p>

What i am trying to do is to put an imagebutton in div which is wider than the button itself and when the outside div is clicked, i want the image button onclick() function to be called. What i expect from below html code is, when i click the button itself, it should alert only "button clicked". when i click the outside div, it should alert "div clicked" first, then "button clicked". The problem is, when i click the div, it alerts: "div clicked" then "button clicked" and then "div clicked" again, in order. When i click the button, it alerts: "button clicked" then "div clicked" then "button clicked" and then "div clicked".

I could not find what i am missing here, any helps?

<html>
<body>
    <div style="width: 200px; border: 1px solid red;" onclick="alert('div clicked');(document.getElementById('addButton')).click();">
        <input type="button" onclick="alert('button clicked');"
            id="addButton"/>
    </div>
</body>
</html>

解决方案

What you've missed is the fact that some events bubble up the document tree triggering all click handlers of parent elements. To stop it, call stopPropagation on the event object.

<input type="button" onclick="event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true);alert('button clicked');"
        id="addButton"/>

(in old IE there is no stopPropagation, you need to set event.cancelBubble=true)

这篇关于使用javascript模拟o​​nclick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆