我们在用到下拉列表框select时,需要对选中的<option>选项触发事件,其实<option>本身没有触发事件方法,我们只有在select里的onchange方法里触发。
想添加一个option的触发事件,在option中添加onclick 点来点去就是不会触发事件
又在select中添加onclick 这下可好了,没选option呢就触发
<select id="pid" οnchange="gradeChange()">
<option grade="1" value="a">选项一</a>
<option grade="2" value="b">选项二</a>
</select>
<script type="text/JavaScript">
function gradeChange(){
var objS = document.getElementById("pid");
var grade = objS.options[objS.selectedIndex].grade;
alert(grade);
}
</script>
<select name="myselect" id="myselect">
<option value="opt1">选项1</option>
<option value="opt2">选项2</option>
<option value="opt3">选项3</option>
</select>
$("#myselect").change(function(){
var opt=$("#myselect").val();
...
});
现在有一id=test的下拉框,怎么拿到选中的那个值呢?
分别使用javascript原生的方法和jquery方法
<select id="test" name="">
<option value="1">text1</option>
<option value="2">text2</option>
</select>
code:
一: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()); //拿到选中项的文本