2017-08-11 67 views
1

我正在使用jQuery開發網頁。在此網頁中,有一個div標籤,其中包含pbutton標籤。如何阻止jQuery中父元素的點擊事件?

HTML碼是這樣的:

<div class="container"> 
    <div id="attribute" style="border:solid;border-width:2px;border-color:#ccc"> 
     <p id="cell-content" style="display:inline">Id</p> 
     <button id="remark-view" class="btn btn-primary">Detail</button> 
    </div> 
</div> 

和相應JavaScript碼是這樣的:

$(document).ready(function(){ 
    $("#attribute").on('click', function(){ 
     console.log("click on the div attribute"); 
    }); 
    $("#attribute").on('dblclick', function(){ 
     console.log("double click on the div attribute"); 
    }); 
    $("#remark-view").on('click', function(){ 
     console.log("click on the button remark-view"); 
    }); 
}); 

作爲代碼所示,一個外div有AP和按鈕子元素,和外部div元素偵聽單擊和雙擊事件,而內部按鈕元素偵聽單擊事件。

當我在瀏覽器中運行代碼並單擊按鈕時,控制檯顯示調用外部div和內部按鈕元素的兩個單擊函數,這違背了我的目的:只有內部按鈕的click功能應該被稱爲在這種情況下。因此,有沒有辦法阻止父元素(在這種情況下,外部div元素)的click事件。換句話說,是否有任何方法可以在子元素處理它之後停止將父事件傳遞給父元素?

預先感謝您!

回答

3

stopPropagation函數將停止冒泡DOM的事件。

$("#remark-view").on('click', function(event){ 
     console.log("click on the button remark-view"); 
     event.stopPropagation() 
    }); 

從jQuery的文檔

冒泡DOM樹,阻止任何 父處理程序被通知的事件阻止事件。

0

這是我在我的一個網站中用來做類似於您的問題的東西。下面的代碼所做的是防止中間的div在按鈕點擊div時關閉。

//Function for the pop up with the background dimmer 
    $(document).mouseup(function(x) { 
    var container = $("#divContent"), 
     dimmer = $('#bgDimmer'); 
    if (container.is(":visible")) { 
     if (!container.is(x.target) //check if the target of the click isn't the container... 
     && container.has(x.target).length === 0) { 
      container.hide(); 
      dimmer.hide(); 
     } 
    } 
}); 

讓我們嘗試與您的代碼相關。

//Function for the pop up with the background dimmer 
    $(document).mouseup(function(x) { 
    var attribute = $('#attribute'); 
    if (attribute.is(":visible")) { 
     if (!attribute.is(x.target) //check if the target of the click isn't the container... 
     && attribute.has(x.target).length === 0) { 
      console.log("click on the button remark-view"); 
     } 
    } 
}); 
+1

答案適用於我的情況,但我認爲當頁面中的點擊監聽器數量增加時,可能會遇到麻煩。傳單提出的方法可能會更好? – pageajpeng

+0

我不明白'attribute.has(x.target).length === 0'的意思。你能解釋它的功能嗎? – pageajpeng

+0

這是爲了檢查容器是否裝滿或我的情況下,我不認爲這將需要你。同意你的更好的答案,但只是作爲一個選項發佈。 – Sand

相關問題