分别用两种方法动态添加option:
方法一:JS方法添加
1、创建select标签
var select = documnet.createElement('select');
2、给select添加id
select.setAttribute('id','selectid');
3、给select添加onchange事件
select.setAttribute('onchange','change();');
4、将select添加到body里面
document.body.appendChild(select);
5、给select里面动态添加option
select.options.add(new Option('label','value'));
方法二:Jquery方法添加
页面已经有select标签,可以直接往里面添加option。
$('#selectid').append('<option value=val>text</option>');
两种方法获取选中的option的值和value
方法一:js方法获取
1、获取select对象
var select = document.getElementById('selectid');
2、获取选中的option的索引值
var index = select.selectedIndex;
3、获取选中option的value
var selectedValue = select.options[index].value;
4、获取选中option的text
vat selectedText = select.options[index].text;
方法二:jQuery方式获取
1、获取选中的option
var select = $('#selectid option:selected');
2、获取选中option的value
var selectValue = select.val();
3、获取选中option的text
var selectedText = select.text();
一个小例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="./js/jquery.min.js"></script>
<script>
window.onload = function(){
//动态的往select里面添加option(JS方式添加)
var select = document.createElement("select");
select.setAttribute('id','sc');
select.setAttribute('onchange','change()');
document.body.appendChild(select);
for(var n = 1;n<10;n++){
select.options.add(new Option('添加option'+n,n+""));
}
//Jquery动态添加option
for(var m = 1;m<10;m++){
$('#selectid').append("<option value="+m+">option"+m+"</option>");
}
change();
}
function change(){
//js方式获取当前选中项
//拿到select的对象
var sel1 = document.getElementById('selectid');
//获取当前选中项的索引
var index = sel1.selectedIndex;
//拿到选中的option的value
console.log(sel1.options[index].value);
//拿到选中的option的text
console.log(sel1.options[index].text);
//Jquery方式获取当前选中项
var sel2 = $('#selectid option:selected');
//拿到选中的option的value
console.log(sel2.val());
//拿到选中的option的text
console.log(sel2.text());
}
</script>
</head>
<body>
<select id='selectid' οnchange="change()" ></select>
</body>
</html>