0

I have a table with some div's inside it.

I want an event to happen when I click on a td element, but I also want an event to happen when I click on a div element. As you can see in this fiddle http://jsfiddle.net/rkGkp/1/ my problem is, when I click on the div element, both the div and td event is triggered, but I only want the div's event to be triggered.

I use these event listeners

$(function() {
    $("#div").on("click", function() {
        alert("a div is clicked");
    });
});
$(function() {
    $(".td").on("click", function() {
        alert("a td is clicked");
    });
});

What can I do to avoid the element behind my div to trigger an event?

4

2 回答 2

3

看看这里:小提琴

我用了stopPropagation()

代码

$("#div").on("click", function(event) {
    event.stopPropagation();
    alert("a div is clicked");
});
于 2013-10-19T15:36:35.127 回答
-1

这是实现您需要的最简单的方法。只需检查点击目标是否在 div 上:

$(function() {
   $("#div").on("click", function() {
       alert("a div is clicked");
   });
});
$(function() {
   $(".td").on("click", function(e) {
      if(!$(e.target).is("#div")){
        alert("a td is clicked");
      }
   });
});
于 2013-10-19T15:42:22.333 回答