js获取select选中的值

获取select选中的内容

// 以下是一个示例的select元素:
// 
// <select id="select">
//     <option value="A" url="http://www.baidu.com">第一个option</option>
    //     <option value="B" url="http://www.qq.com">第二个option</option>
    // </select>

一:JavaScript原生的方法

// 1. 拿到select对象:
// var myselect = document.getElementById("select");

// 2. 拿到选中项的索引:
// var index = myselect.selectedIndex;
// 注释:selectedIndex代表的是你所选中项的index

// 3. 拿到选中项options的value:
// var selectedValue = myselect.options[index].value;

// 4. 拿到选中项options的text:
// var selectedText = myselect.options[index].text;

// 5. 拿到选中项的其他值,比如这里的url:
// var selectedURL = myselect.options[index].getAttribute('url');

二:jQuery方法

// 1. 获取选中的项:
// var options = $("#select option:selected");

// 2. 拿到选中项的值:
// alert(options.val());

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

// 4. 拿到选中项的url值:
// alert(options.attr('url'));

posted on 2020-07-19 18:24  完美前端  阅读(1932)  评论(0)    收藏  举报

导航