簡體   English   中英

如何通過單擊 select 選項訪問 select 框中的屬性名稱值

[英]How to access the property name's value in select box by clicking select option

我想訪問 name 屬性及其值。 當我點擊 select 標簽時。 這是示例代碼

<select name="abc" id="input-abc"  onChange={(e)=>handleSelectButton(e)}>
  <option value="green" name="apple" >Apple</option>
  <option value="yellow" name="banana" >Banana</option>
</select>

function handleSelectButton(e) {
        console.log(e.target.value);
    } 

如果我會 select Apple 那么名字就是蘋果應該來。 我只能訪問值,但如何訪問 name 屬性值。 我試過e.target.getAttribute("name")

知道如何解決這個問題嗎? 提前致謝。

這行得通!

 function handleSelectButton(e) { console.log(e.target.selectedOptions[0].getAttribute("name")); }
 <select name="abc" id="input-abc" onChange="handleSelectButton(event)"> <option value="green" name="apple">Apple</option> <option value="yellow" name="banana">Banana</option> </select>

這是最簡單的解決方案。 如果您有任何問題,請隨時發表評論。

 function getAttribute() { var x = document.getElementsByTagName("option")[0].getAttribute("name"); var y = document.getElementsByTagName("option")[1].getAttribute("name"); console.log(x); // [0] is the first option tag console.log(y); // [1] is the second option tag } getAttribute()
 <select name="abc" id="input-abc" onChange={(e)=>handleSelectButton(e)}> <option value="green" name="apple">Apple</option> <option value="yellow" name="banana">Banana</option> </select>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM