2012-10-11 46 views
9

我試圖註銷我已經附加到我的選擇框中的每個選項的數據屬性,但沒有成功,我正確使用.on('改變'...或者我應該怎麼做到這一點?如何在select中返回選項元素的數據屬性?

JS

$('select').children().on('change', function(e){ 
    console.log($(this).data('id')); 
    e.preventDefault(); 
}); 

HTML

<select> 
<option value="1" data-id="option1">wgwg</option> 
<option value="1" data-id="option2">wgwerg</option> 
<option value="1" data-id="option3">wgwg</option> 
<option value="1" data-id="option4">wgr</option> 
</select>​ 

回答

20

option改變事件並沒有真正意義的option沒有改變。該事件應該在select上。

$('select').on('change', function(e){ 
    console.log($(this).find("option:selected").data('id')); 
    e.preventDefault(); 
}); 
1

試試這個,

Live Demo

$('select').on('change', function(e){ 
    console.log($('option:selected', this).data('id')); 
    e.preventDefault(); 
}); 
1

你似乎對事件指定的選擇孩子這是不對的.. 您需要將事件指派給直接選擇..

而且this沒有數據屬性。這是option that is selected ..所以,你的代碼改成這樣

試試這個

$('select').on('change', function(e){ 
     console.log($(this).find('option:selected').attr('data-id')); 
    }).change(); 

OR

$('select').on('change', function(e){ 
      console.log($(this).find('option:selected').data('id')); 
     }).change(); 
+0

'this'是選擇和選擇不具有'數據id'。 –

+0

補充說..謝謝 –

1

您與香草的Javascript就可以了:

console.log(this.querySelector(':checked').getAttribute('data-id')) 
相關問題