2014-02-25 123 views
0

比方说,我为HTML div获得了一个简单的点击事件。 如果我点击div,它应该会触发fadeToggle。jquery禁用div的点击事件

在那个div里,我用另一个触发器获得了另一个div。 在那个点击事件上,它应该做一些事情,而不是做事件触发第一个事件。

如果我希望事件2触发,如何防止事件1触发?

只有当我不按第二个事件的clickevent时,Event1才会触发,其他所有事件都应该像平常一样触发。

感谢您的时间

HTML

<div id="1"> 
    Event 1 
    <div id="2"> 
     <div id="3"> 
      but here is something as well event2 
      </div> 
    </div> 
</div> 

的JavaScript

$("#1").click(function() { 
    $(this).slideToggle(); 
}); 


$("#3").click(function() { 
    $(this).css("background-color", "blue"); 
}); 

小提琴:http://jsfiddle.net/VLcxJ/

回答

1
$("#3").click(function(e) { 
    e.stopPropagation(); 
    $(this).css("background-color", "blue"); 
}); 

之后,点击#3将不会到达#2或#1

+1

谢谢开始。帮助我,我可以在11分钟内接受你的答案。 –

0
$("#3").click(function(event) { 
    event.stopPropagation(); 
    $(this).css("background-color", "blue"); 
}); 

新增小提琴:http://jsfiddle.net/VLcxJ/1/

+0

这与我写的基本上是一样的:) – kamilkp

+0

当然,当我提交答案的时候,我的浏览器还没有,这并不意味着要窃取任何东西。 –

-1

下面是解

 $("#1").click(function() { 
      $(this).slideToggle(); 
     }); 


     $("#3").click(function(event) { 
      event.stopPropagation(); 
      $(this).css("background-color", "blue"); 
     }); 

http://jsfiddle.net/tR7h9/3/

2

使用event.stopPropagation();

$("#e3").click(function(event) { 
    event.stopPropagation(); 
    $(this).css("background-color", "blue"); 
}); 

看到它在这里工作:http://jsfiddle.net/bYn22/

注意从jQuery的API(我不能更好地解释它):event.stopPropagation()>冒泡DOM树,阻止任何阻止事件家长处理者不会被通知事件。

并注意您的ID不能与一些 :)

+0

如果你添加一个解释他为什么应该使用'event.stopPropagation();'现在你的答案看起来像:添加这个代码,它会工作 – Yang

+0

当然,它总是很好的知道。 – enguerranws

+0

那么,因此+1 – Yang