2014-09-03 66 views
1

我想单独单击事件。javascript单击事件分隔

所有的body标签中点击要警惕“表外”,

除了内部postit-table类的Click事件。

这是我的代码:

HTML

<table class="postit-table"> 
    <tbody> 
    <tr class="postit-header"> 
     <td>header</td> 
    </tr> 
    <tr> 
     <td><textarea class="postit-content"></textarea></td> 
    </tr> 
    </tbody> 
</table> 

CSS

.postit-table{ 
    width: 200px; 
    height: 200px; 
    background-color: yellow; 
} 

的JavaScript(jQuery的):

$("body").bind('click',':not(".postit-table,.postit-table tbody, .postit-table tr, .postit-table tbody tr td")', function (e) { 
    alert("clicked outside table!"); 
}); 

$(".postit-table").click(function(){ 
    alert("clicked inside table!"); 
}); 

的jsfiddle:

http://jsfiddle.net/c5fomgp1/

不幸的是,如果你运行的小提琴应用程序,它仍然调用外部表的单击事件:(

有人可以帮忙吗?

回答

3

postit-table点击事件中使用stopPropagation(): 这样的单击事件将不会传播冒泡到body元素

示例 - http://jsfiddle.net/e5jph1Lt/

$("body").on('click', function() { 
    alert("clicked outside table!"); 
}); 

$(".postit-table").on('click', function(evt) { 
    evt.stopPropagation(); 
    alert("clicked inside table!"); 
}); 

一点题外话,使用on()代替bind()如果您使用最近的jQuery版本

0

看起来过于复杂的我。正如其他人已经回答你可以使用event.stopPropagation简化你的代码。喜欢的东西:

$(document).on('click', clickedoutside); 
$('body').on('click', '.postit-table', clicked); 

function clicked(e){ 
    e.stopPropagation(); 
    alert('clicked inside table!'); 
}; 

function clickedoutside(e){ 
    alert('clicked <b>outside</b> table!'); 
}; 

这是你改写jsFiddle

3

解决

$("body").bind('click',':not(".postit-table,.postit-table tbody, .postit-table tr, .postit-table tbody tr td")', function (e) { 
    alert("clicked outside table!"); 
}); 

$(".postit-table").click(function(e){ 
    e.stopPropagation(); 
    alert("clicked inside table!"); 
}); 

也尽量来回这有其他的解决办法。 Chears