简体   繁体   English

jQuery禁用div的点击事件

[英]Jquery disable click event for div

Let's say I got a simple click event for a HTML div. 假设我有一个HTML div简单的click事件。 If I click on the div it should trigger a fadeToggle. 如果单击div,则应触发fadeToggle。

In that div I got another div with another trigger. 在那个div中,我有另一个带有另一个触发器的div。 On that click event it should do something but instead of doing the event it triggers the first event. 在该click事件上,它应该执行某些操作,但它会触发第一个事件,而不是执行该事件。

How do I prevent event 1 from triggering if I want event2 to trigger? 如果我想触发事件2,如何防止事件1触发?

Event1 should trigger only if I don't press the clickevent on the second event everything else should trigger as usual. 仅当我没有在第二个事件上按下clickevent时,Event1才应触发。

Thanks for your time 谢谢你的时间

HTML 的HTML

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

JavaScript 的JavaScript

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


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

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

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

After that, clicks on #3 won't reach #2 or #1 之后,点击#3将不会到达#2或#1

Use event.stopPropagation(); 使用event.stopPropagation(); :

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

See it working here : http://jsfiddle.net/bYn22/ 看到它在这里工作: http : //jsfiddle.net/bYn22/

Note from jQuery API (I couldn't explain it better) : event.stopPropagation() > Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. jQuery API的注意事项 (我无法更好地解释它):event.stopPropagation()> 防止事件使DOM树冒泡,从而防止任何父处理程序收到该事件的通知。

And note that your IDs can't begin with a number :) 请注意,您的ID不能以数字开头 :)

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

Added Fiddle: http://jsfiddle.net/VLcxJ/1/ 添加了小提琴: http : //jsfiddle.net/VLcxJ/1/

Here is the solution 这是解决方案

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


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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM