2014-09-23 81 views
1

我與選擇框的工作過程中一個選擇框訪問的數據值與JavaScript onchange事件如下圖所示,如何onchange事件

<select onchange="changeprice(this);" > 
    <option value="" selected="">Please select an option</option> 
    <option value="17" data-operator="+" data-differ="0.00">2 Tons (+ $0.00)</option> 
    <option value="18" data-operator="-" data-differ="125.00">5 Tons (- $125.00)</option> 
</select> 

我設法調用功能沒有問題,但在活動期間我希望得到數據屬性,而不是價值,我不能讓它工作,因爲預計 下面是我目前的JavaScript

<script> 
function changeprice($this){ 

alert("test");//successfully alerted 
alert($this.data-differ);//no respond 
alert($this.data("operator"));//no respond 
alert($this.data("differ"));//no respond 

}; 
</script> 

請告知

+0

@CasBloem我試過了$($ this).data(「differ」)但它給我undefined – 2014-09-23 13:28:27

回答

1

,你可以這樣做:

<script> 
function changeprice(element){ 

var op = $(element).find("option:selected").data("operator") 
var diff = $(element).find("option:selected").data("differ") 

}; 
</script> 
+0

謝謝你的代碼工作沒有什麼變化,我不明白不同但它修復了我的工作 我必須將元素更改爲$元素 – 2014-09-23 13:37:38

0

我會假設你正在使用jQuery。如果是這樣,您可以訪問使用

$($this).data("differ") 

沒有jQuery的數據的屬性,它可能看起來像

// For newer browsers 
$this.dataset.differ 

// For older IE's, check http://caniuse.com/#feat=dataset where you need to use this solution 
$this.getAttribute("data-differ") 
0

您可以GTE不同的屬性和值如下:

$($this).find(':selected').attr('data-operator'); 
$($this).find(':selected').attr('data-differ'); 
$($this).find(':selected').val();