繁体   English   中英

如何获取选项的属性

[英]How to get the attribute of an option

我已经使用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给了我null

您可以先获取selected选项的引用,然后使用getAttribute()

ele.options[ele.selectedIndex].getAttribute('price')

但是,我建议您使用data-*前缀属性

<option value="${arr[i].name}" data-price="${arr[i].price}">${arr[i].name}</option>

然后可以使用Element.dataset属性。

var price = ele.options[ele.selectedIndex].dataset.price

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM