两个不同点击两个div,一个在另一个之上 [英] Two differents OnClick on two divs, one over the other
本文介绍了两个不同点击两个div,一个在另一个之上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个div,一个是大的,另一个是小的,每个div都有自己的OnClick方法。我遇到的问题是当我点击较小的div时,大div的OnClick方法也被调用。
谁能避免这种情况?
检测被点击的元素是分析事件的目标(点击事件)。我为这个案例准备了一个小例子。
函数amIclicked(e,element)
{
e = e ||事件;
var target = e.target || e.srcElement;
if(target.id == element.id)
return true;
else
返回false;
}
函数oneClick(event,element)
{
if(amIclicked(event,element))
{
alert('One is clicked' );
函数twoClick(event,element)
{
if(amIclicked(event,element))
{
alert( '点击两下');
$ b这个javascript方法可以在你执行你的脚本之前被调用
示例
< style>
#one
{
width:200px;
height:300px;
背景颜色:红色;
}
#two
{
width:50px;
height:70px;
background-color:yellow;
margin-left:10;
margin-top:20;
}
< / style>
< div id =oneonclick =oneClick(event,this);>
one
< div id =twoonclick =twoClick(event,this);>
two
< / div>
< / div>
我希望这有助于。
I have two divs, a big one and a smaller over the other, each div has its own OnClick method. The problem I have is when I clicked the smaller div, the big div's OnClick method is called too.
Who can I avoid that?
解决方案
The best way to detect which element was clicked is to analyze target of event ( click event ). I have prepared small example for this case. You can see it in code below.
function amIclicked(e, element) { e = e || event; var target = e.target || e.srcElement; if(target.id==element.id) return true; else return false; } function oneClick(event, element) { if(amIclicked(event, element)) { alert('One is clicked'); } } function twoClick(event, element) { if(amIclicked(event, element)) { alert('Two is clicked'); } }
This javascript method can be called before you execute your script
Example
<style> #one { width: 200px; height: 300px; background-color: red; } #two { width: 50px; height: 70px; background-color: yellow; margin-left: 10; margin-top: 20; } </style> <div id="one" onclick="oneClick(event, this);"> one <div id="two" onclick="twoClick(event, this);"> two </div> </div>
I hope this helps.
这篇关于两个不同点击两个div,一个在另一个之上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文