<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:
myselect.options[index].value;
4:拿到選中項options的text:
myselect.options[index].text;
5:拿到選中項的其他值,比如這裏的url:
myselect.options[index].getAttribute('url');
二.jQuery方法
var options=$(“#select option:selected”); //獲取選中的項
alert(options.val()); //拿到選中項的值
alert(options.text()); //拿到選中項的文本
alert(options.attr('url')); //拿到選中項的url值
jQuery對象轉換成js對象:轉換後,使用js的方法。
(1)jQuery對象是一個數據對象,可以通過[index]的方法,來得到相應的js對象。
如:
var $v = $("#v") ; //jQuery對象
var v=$v[0]; //js對象
(2)jQuery本身提供,通過.get(index)方法,得到相應的js對象
如:
var $v= $("#v"); //jQuery對象
var v=$v.get(0); //js對象
js對象轉成jQuery對象: 轉換後,使用jQuery的方法。
對於一個js對象,只需要用 $ ()把DOM對象包裝起來,就可以獲得一個jQuery對象了。$(js對象)
如:
var v=document.getElementById("v"); //js對象
var $v=$(v); //jQuery對象