[英]How to get the attribute of an option
I have create a dynamic dropdown using JS 我已经使用JS创建了动态下拉列表
var str = `<select onchange="getPrice(this)"><option value="">Select</option>`;
for(var s=0;s<arr.length;s++) {
str += `<option value="${arr[i].name}" price="${arr[i].price}">${arr[i].name}</option>`;
}
str += '</select>
function getPrice(ele) {
console.log(ele.value); //getting the value here
console.log(ele.price); //getting null here
}
ele.price
is giving me null ele.price
给了我null
You can first get the reference of selected
option then use getAttribute()
您可以先获取selected
选项的引用,然后使用getAttribute()
ele.options[ele.selectedIndex].getAttribute('price')
However, I would recommend you to use data-*
prefixed attribute 但是,我建议您使用data-*
前缀属性
<option value="${arr[i].name}" data-price="${arr[i].price}">${arr[i].name}</option>
then Element.dataset
property can be used. 然后可以使用Element.dataset
属性。
var price = ele.options[ele.selectedIndex].dataset.price
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.