簡體   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