2014-09-02 73 views
1

在每個jQuery事件中,jQuery提供的currentTargetthis相同,但據我瞭解currentTarget的屬性取決於您的瀏覽器。jQuery事件currentTarget數據集

在chrome中,我可以得到event.currentTarget.dataset,它給了我啓動事件的元素的數據,但我不認爲這適用於所有瀏覽器。我所知道的唯一的跨瀏覽器解決方案是通過將currentTarget包裝到另一個像下面的jQuery對象中來獲取數據。

var div = jQuery("<div/>").data("numbers", [1,2,3]); 
div.click(function(e) { 
    var data = jQuery(e.currentTarget).data(); 
    console.log(data.numbers); 
}); 

有誰知道一個跨瀏覽器的解決方案來獲取數據,而無需創建與this/currentTarget一個新的jQuery對象?

更新:只是要清楚,我之所以問:

我們正在轉換是再次觸發事件轉換爲一個jQuery對象元素,發送它通過jQuery的第二次(已經是一個jQuery對象來創建事件)。我希望能夠將已經創建的jQuery對象帶入事件中。幻燈片44 & 45上this presentation解釋我的思維過程。

你可以用event.currentTarget.dataset來做到這一點,但我不認爲它是一個跨瀏覽器的解決方案。在上面的代碼中,您可以使用緩存的jQuery對象div來獲取數據而不重新創建jQuery對象。這適用於特定的例子,但你會用像下面的delegate事件動態事件做:

jQuery("#container").on('click', '.pop-data', function(e) { 
    var data = jQuery(e.currentTarget).data(); 
    alert(data); 
}); 

上面的代碼工作,而不是一個壞的解決方案,但沒有人知道的方式來獲取數據,而不創建一個新的jQuery對象?

+0

爲什麼你想要一個不同的解決方案? – 2014-09-02 06:42:18

+0

jquery被寫入使用的方式有什麼問題? – 2014-09-02 06:45:33

+0

@arun表演。它的一個插件。 – Dol 2014-09-02 06:47:41

回答

0

在接受的答案往下看的

Having problems in IE8 when attempting to get data from target event

jQuery("#container").on('click', '.pop-data', function(e) { 
    console.log($(e.target).attr('data-numbers')); 
}); 

就個人而言,我無法得到的。數據()jQuery的東西的工作(不知道爲什麼),但上述作品產生粘HTML屬性內聯。

<img src='...' data-numbers='1'> 
+0

感謝您的貢獻。不幸的是我使用的jQuery數據稍有不同,我沒有將它附加到數據屬性上,我使用jQuery數據方法將它附加到腳本中進行設置。我正在尋找的答案是如何從事件中攜帶的事件變量(e)中訪問數據,而不是再次將其包裝在jQuery函數中。它是可訪問的,但是通過currentTarget中的一個名爲dataset的數據屬性,我不確定是在每個瀏覽器中執行的。 – Dol 2015-03-20 08:24:47

+0

您可以通過調用不含「數據」的數據來獲取數據,並將其餘數據轉換爲較低的駱駝大小寫。但在你的情況下使用getAttribute on target或currentTarget(沒有jQuery)更好。我認爲這種方法可以追溯到IE 5。 – Dol 2015-03-20 08:25:21