2013-12-20 44 views
1

我得到了一個雙重事件來管理。這兩個事件都是「點擊」,並用jquery進行處理。 html是以下內容:用jquery捕獲事件

<div class="siteMap" style="width:23%;"> 
      <h5>Divisione Anticontraffazione</h5> 
      <span class="menufooter"> 
      <span class="link1"><a href="#scheda1">Introduzione</a></span><br> 
      <span class="link2"><a href="#scheda2">Filosofia</a></span><br> 
      <span class="link3"><a href="#scheda3">Negozio online</a></span></span><br> 
     </div> 

然後我有我的點擊事件在menufooter範圍內和每個單鏈接範圍內觸發。該代碼是這樣的:

$(document).ready(function() { 
    $('span.menufooter').click(function() { 
     //my code here 
    }); 
    $("span.link1").click(function() { 
     //my code here 
    }); 
}); 

我需要一個事件捕捉動作,上menufooter對跨度LINK1火災點擊之前觸發事件跨度點擊。在這一點上,兩個事件都沒有發射。任何提示?

+1

爲什麼你需要有一個事件處理器執行在另一個之前,以錯誤的順序? – adeneo

+0

我的回答沉重的時刻,重新思考。謝謝@Barmar。 – Swires

+0

也許可以解釋一下你的意圖,以便更好地瞭解如何改進你的應用。 – isherwood

回答

1

您可以防止點擊冒泡,然後觸發父元素因此無論是在處理程序上點擊先執行(除非它是異步)

$(document).ready(function() { 
    $('.menufooter').click(function() { 
     // fires before .... 
    }); 

    $("span.link1").click(function (e) { 
     e.stopPropagation(); 
     $('.menufooter').trigger('click'); 
     // .... this fires, as it's triggered above 
    }); 
}); 

FIDDLE

0

試試這個event.stopPropagation();

$("span.link1").click(function(event) { 
    event.stopPropagation(); 
     ... 
}); 
0

我將有一個監聽器來監聽包裝器。您可以檢查事件的目標,看看他們是否實際點擊了鏈接並相應地運行代碼。

例如:

$(document).ready(function() { 

    $('.container').click(function(e) { 

     // Perform action when they clicked in the main wrapper, 
     // regardless of whether or not it was a link. 
     console.log("I clicked in the wrapper..."); 

     if ($(e.target).hasClass('link')) { 
      // Perform action if they clicked on a link. 
      console.log("...but more specifically, on a link."); 
     } 
    }); 

}); 

下面是說明了這一點小提琴:http://jsfiddle.net/WaYFr/

4

如何只有火災事件上.menufooter

$(document).ready(function() { 
    $('span.menufooter').click(function(e) { 
     //my code here 1 

     // Capture Event Propagation 
     if ($("span .link1").find(e.target).length>0){ 
      //my code here 2 
     }; 
    }); 
}); 

http://jsfiddle.net/9QLtG/