选择框上的数据属性 returns 未定义

Data attribute returns undefined on selectbox

我正在尝试 运行 一个函数,一旦用户点击了我的 select 框的某个选项上方。然而,我试图使用数据属性和 jQuery 来实现这一点,但它不起作用。

这是代码:

<select class="form-control" id = "add-languages" style = "margin-top:5px;">
                                    <option value = "">(Select your additional language)</option>
                                    <option value = "en" data-langfullname = "english">English (by default)</option>
                                    <option value = "es" data-langfullname = "spanish">Spanish</option>
                                    <option value = "gr" data-langfullname = "german">German</option>
                                    <option value = "ch" data-langfullname = "chinese">Chinese</option>
                                    <option value = "ru" data-langfullname = "russian">Russian</option>
                                    <option value = "jp" data-langfullname = "japanese">Japanese</option>
                                    <option value = "fr" data-langfullname = "french">French</option>
                                    <option value = "pt" data-langfullname = "portuguese">Portuguese</option>


$(function(){
        $("#add-languages").change(function(){
            alert($(this).data("langfullname"));

        });
    });

这是我的Fiddle...谢谢

http://jsfiddle.net/BTtN8/30/

使用 this,您正在尝试访问 <select> 的数据属性。相反,您需要访问所选 <option>.

的数据属性
$('option:selected',this).data("langfullname");

在下面试试:

$(function() {
  $("#add-languages").change(function() {
    alert($('option:selected', this).data("langfullname"));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select class="form-control" id="add-languages" style="margin-top:5px;">
  <option value="">(Select your additional language)</option>
  <option value="en" data-langfullname="english">English (by default)</option>
  <option value="es" data-langfullname="spanish">Spanish</option>
  <option value="gr" data-langfullname="german">German</option>
  <option value="ch" data-langfullname="chinese">Chinese</option>
  <option value="ru" data-langfullname="russian">Russian</option>
  <option value="jp" data-langfullname="japanese">Japanese</option>
  <option value="fr" data-langfullname="french">French</option>
  <option value="pt" data-langfullname="portuguese">Portuguese</option>
  <option value="it" data-langfullname="italian">Italian</option>
  <option value="po" data-langfullname="polish">Polish</option>
  <option value="tu" data-langfullname="turkish">Turkish</option>
  <option value="du" data-langfullname="dutch">Dutch</option>
  <option value="ar" data-langfullname="arabic">Arabic</option>
  <option value="ko" data-langfullname="korean">Korean</option>
</select>