[英]How to get selected option data attribute from HTML select
I am working on the below code.我正在处理以下代码。 Why am I not able to get the selected option's data attribute?
为什么我无法获得所选选项的数据属性?
$('#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>
$(this)
will return the select itself, which has no data-filter
, you need to get the selected option to obtain its filter attribute $(this)
将返回 select 本身,它没有data-filter
,您需要获取 selected 选项以获取其过滤器属性
$('#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>
You are getting the data attribute of the select
, not the option
.您正在获取
select
的 data 属性,而不是option
。 Use $("#type-picker option:selected")
.使用
$("#type-picker option:selected")
。
$('#type-picker').on('change', function (e) {
var filter = $("#type-picker option:selected").data("filter");
console.log(filter);
});
Working Example: https://jsfiddle.net/mspinks/zdng9s5o/2/工作示例: https : //jsfiddle.net/mspinks/zdng9s5o/2/
You need to get the selected <option>
inside the <select>
.您需要在
<select>
获取选定的<option>
<select>
。 this
keyword references the <select>
this
关键字引用了<select>
Here's how you can do it without jQuery这是没有 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.