jQuery数据元素总是未定义,为什么

时间:2015-10-13 14:53:00

标签: jquery html

我查看了很多帖子,但看不出我在做什么,这与其他地方的建议不同。

我有以下内容:

<select class="SS2" name="nSS">
    <option class="SSO" data-section="1" selected="selected" disabled="disabled">Select an Option</option>
    <option class="SSO" data-section="1" value="1">option 1</option>
    <option class="SSO" data-section="1" value="2">option 2</option>
</select>
</br>

然后我有以下jQuery:

<script>
$(document).ready(function() {
    $('body').on('change', '.SS2', function() {
        var id1 = $(this).data('section');
        var id2 = $(this).val();
        alert(id1);
        alert(id2);
    })
});
</script>   

当它运行alert(id1)时,它会显示为未定义,但alert(id2)按预期工作。 任何人都可以解释为什么我无法拿起data('section')

我也尝试过使用$(this).attr('data-section')

1 个答案:

答案 0 :(得分:4)

事件处理程序中的

$(this)引用了<select>元素,该元素不具有data-section属性。

要获取所选<option>的值,您可以使用option:selected选择器。

var id1 = $(this).children('option:selected').data('section');

<强>演示

&#13;
&#13;
$(document).ready(function() {
  $('body').on('change', '.SS2', function() {
    var id1 = $(this).children('option:selected').data('section');
    var id2 = $(this).val();
    alert(id1);
    // alert(id2);
  })
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="SS2" name="nSS">
  <option class="SSO" data-section="1" selected="selected" disabled="disabled">Select an Option</option>
  <option class="SSO" data-section="1" value="1">option 1</option>
  <option class="SSO" data-section="1" value="2">option 2</option>
</select>
&#13;
&#13;
&#13;