简体   繁体   English

jQuery将函数绑定到父div,但不绑定子锚,反之亦然

[英]jQuery bind function to parent div but not child anchor and vice-versa

I have a div, inside of which are a few anchor links: 我有一个div,其中有一些锚点链接:

<div id="myDiv">
+----------------------------+
|                            |
|  <a class="myAnc">...</a>  |
|  <a class="myAnc">...</a>  |
|                            |
+----------------------------+

I want to bind a click event to #myDiv that calls myFunction1() but have .myAnc tags call myFunction2() . 我想将单击事件绑定到#myDiv ,该事件调用myFunction1()但具有.myAnc标记调用myFunction2() Using jQuery's bind , what happens is that both myFunction1 and myFunction2 are called no matter what you click on (the div or the anchor). 使用jQuery的bind ,无论单击什么(div或锚点),都会调用myFunction1myFunction2

How can I make sure that they call on their two separate functions (and only those functions)? 如何确保它们调用两个单独的函数(并且仅调用那些函数)?

myFunction2(ev)调用中:

ev.stopPropagation();

Try this: 尝试这个:

$("a.myAnc").click(function(e) {
   e.stopPropagation(); // prevent DOM event bubbling which will trigger the click of the parent div
});

$("#myDiv").click(function() {
});
$('#myDiv, a.myAnc').click(function(event) {
   event.stopPropagation(); // Prevent bubbling to #myDiv

   alert('you click  ' + $(this));
});

Try 尝试

$(".myAnc").bind("click",
                         function()
                         {
                             myFunction2();
                             return false;
                         }
                        );

    }

Working demo @ http://jsfiddle.net/NeLsE/ 工作演示@ http://jsfiddle.net/NeLsE/

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

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