2016-01-23 19 views
0

我有一個名爲itemID的自定義屬性 - 我如何獲得它的值,所以我可以把它放在類似於我如何獲得id的URL中?從jquery事件獲取自定義數據

JS:

<script type="text/javascript"> 
$(document).ready(function(){ 
    $('.eventImage').click(function(e){ 
    $this = $(this); 
     $.ajax({ 
     url: "http://server.local/action.php?event="+$this.attr("id")+"&itemID="+$this.data('itemID'), 
     type:'POST', 
     }); 
    }); 

}); 
</script> 

HTML:

<img class='eventImage' id='ITEM_3_ON' src='images/livingroom/1-2.png' data-itemID='3'/> 
+0

'電子!= event'在所有瀏覽器時,有沒有孩子這IMGE不能有 – charlietfl

回答

0

你需要給它以這樣的方式

$(document).ready(function(){ 
    $('.eventImage').click(function(e) { 
     $this = $(this); // Make a copy of the image. 
     $.ajax({ 
     url: "http://server.local/action.php?event="+$this.attr("id")+"&itemID="+$this.data('itemID'), // Use $this here. 
     type:'POST', 
     }); 
    }); 
}); 

變化:

01我猜,有改變的傾向,因爲你在AJAX的回調函數裏面調用。

  1. 使用$this來引用AJAX調用中的當前對象。
  2. 使用相同的$this也可以得到id
+0

目標不能改變 – charlietfl

+0

ITEMID是顯示爲未定義 –

+0

@ johncs你使用的是什麼版本的jQuery? –

-1

如果你想使用被轉移的事件,那麼你應該使用e.target.id和屬性e.target.attributes ['data-itemID']。value not event.target.id當你轉移e進入點擊處理函數..

請注意,e.target返回一個javascript對象而不是jquery對象。

+0

而不是傳遞值3,它通過這個:[object%20Attr] –

+0

我編輯了代碼...現在它會正常工作 –

0

我認爲$this.attr("data-itemID")是解決..