2014-09-03 64 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