无法从HTML选择获取选定的选项数据属性

时间:2017-01-26 18:52:14

标签: javascript jquery

您能否请一看这个演示,让我知道为什么我无法获得所选选项的数据属性?



$('#type-picker').on('change', function (e) {
  var filter =  $(this).data("filter");
  console.log(filter);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="selectpicker" id="type-picker" data-width="100%" >
  <option data-filter="na" >Select From The List</option>
  <option data-filter="*">Display ALl</option>
  <option data-filter=".type1">Relish</option>
  <option data-filter=".type2">Relish</option>
  <option data-filter=".type3">Relish</option>
</select>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:3)

$(this)将返回select本身,它没有data-filter,您需要获取所选的选项以获取其过滤器属性

$('#type-picker').on('change', function (e) {
  var filter =  $(this).find('option:selected').data("filter");
  console.log(filter);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="selectpicker" id="type-picker" data-width="100%" >
  <option data-filter="na" >Select From The List</option>
  <option data-filter="*">Display ALl</option>
  <option data-filter=".type1">Relish</option>
  <option data-filter=".type2">Relish</option>
  <option data-filter=".type3">Relish</option>
</select>

答案 1 :(得分:1)

您将获得select的数据属性,而不是option。使用$("#type-picker option:selected")

$('#type-picker').on('change', function (e) {
  var filter =  $("#type-picker option:selected").data("filter");
  console.log(filter);
});

工作示例:https://jsfiddle.net/mspinks/zdng9s5o/2/

答案 2 :(得分:0)

您需要在<option>内获取所选的<select>this个关键字引用了<select>

这是你如何在没有jQuery的情况下做到这一点

$('#type-picker').on('change', function (e) {
  var filter = this.children[this.selectedIndex].dataset.filter
  
  // this would also work
  //var filter = this.selectedOptions[0].dataset.filter
  
  console.log(filter);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="selectpicker" id="type-picker" data-width="100%" >
  <option data-filter="na" >Select From The List</option>
  <option data-filter="*">Display ALl</option>
  <option data-filter=".type1">Relish</option>
  <option data-filter=".type2">Relish</option>
  <option data-filter=".type3">Relish</option>
</select>