2017-01-02 90 views
0

如何將事件從mouseup事件傳遞給函數?傳遞事件到功能?

到目前爲止我的代碼

$(".add, .remove").on("mouseup", getCart); 

function getCart(e) 
{ 
    post_data = {"id" : e.attr('data-productNumber'), "action" : e.attr('data-action')} 
} 

我得到一個TypeError: Cannot read property 'attr' of undefined。所以我猜測事件沒有得到通過。

+0

這裏你沒有傳遞任何參數給函數。這就是爲什麼它拋出一個錯誤 –

+1

您必須註冊功能,而不是它的呼叫:'getCart',而不是'getCart()' –

+0

@DenysSéguret我刪除了parenteses,並獲得「e.attr是不是一個函數」現在 – vandelay

回答

2

事件對象不具有和attr方法。您可能需要e.target來引用獲取該事件的元素。一個jQuery元素將有attr方法。

所以:

$(e.target).attr('data-productNumber') 

...等。

如果目標元素是一樣的,你有選擇的元素,即與添加刪除類,你也可以使用this

$(this).attr('data-productNumber') 

注:jQuery的loads the data- attributes在它的數據對象中,所以你可以這樣做:

$(e.target).data('productNumber') 
$(this).data('productNumber') 
+0

你怎麼知道這是關於目標?它可能只是'this',或任何其他 –

+0

謝謝,該作品:) – vandelay

+0

不客氣;-) – trincot

-2

將目標元素傳遞給函數。

$(".add, .remove").on("mouseup", getCart($(".add, .remove"))); 

function getCart(e) 
{ 
    post_data = {"id" : e.attr('data-productNumber'), "action" : e.attr('data-action')} 
} 
+0

這是錯誤的。你測試過了嗎? – trincot

+0

這是對我的作品.. –

+0

http://jsbin.com/gepatekupi/edit?html,js,output –