2014-02-25 132 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