1. 程式人生 > >獲取seleect下選中option的屬性值

獲取seleect下選中option的屬性值

cte 原生 eth 中項 2.3 tle clas script https

<!DOCTYPE html>
<html>
<head>
    <title></title>
        <script src="https://cdn.bootcss.com/vue/2.3.3/vue.min.js"></script>
</head>
<body>
<div id="app">
  <select v-model="value" placeholder="請選擇" @change="handlueCahnge">
    <option 
v-for="(item, index) in options" :label="item.label" :value="item.value" :other="item.label" :data-love="item.id"> </option> </select> </div> <script type="text/javascript"> var vm = new Vue({ el: "#app", data: { options: [{ id:"1", value: 選項1
, label: 黃金糕 }, { id:"2", value: 選項2, label: 雙皮奶 }, { id:"3", value: 選項3, label: 蚵仔煎 }, { id:"4", value: 選項4, label: 龍須面 }, { id:"5", value: 選項5, label: 北京烤鴨 }], value: ‘‘ }, methods: { handlueCahnge(e) { console.log(e) console.log(e.target) console.log(e.target.value) console.log(e.target.selectedOptions[
0].dataset.love) console.log(e.target.selectedOptions[0].getAttribute("data-love") ) var a=e.target.selectedIndex console.log(e.target.options[a].dataset.love) } } }) </script> </body> </html>

主要用到 selectedOptions 和 selectedIndex 2種方法,看代碼即可明白。

另轉載:

如何獲得select被選中option的value和text

一:JavaScript原生的方法

1:拿到select對象: var myselect=document.getElementById(“test”);

2:拿到選中項的索引:var index=myselect.selectedIndex ; // selectedIndex代表的是你所選中項的index

3:拿到選中項options的value: myselect.options[index].value;

4:拿到選中項options的text: myselect.options[index].text;

二:jQuery方法(前提是已經加載了jquery庫)

1:var options=$(“#test option:selected”); //獲取選中的項

2:alert(options.val()); //拿到選中項的值

3:alert(options.text()); //拿到選中項的文本

參考鏈接:http://www.cnblogs.com/zhaokuojiao/p/6055632.html

獲取seleect下選中option的屬性值