js里面的dom操作中这几项是比较特殊的。
添加select
window.οnlοad=function(){
var select=document.createElement("select");
select.setAttribute("id","selectnew");
document.getElementsByTagName("body")[0].appendChild(select);
}
添加选项
window.οnlοad=function(){
var select=document.getElementById("selectnew");
select.options.add(new Option("text","value"));
}
删除选项
window.οnlοad=function(){
var select=document.getElementById("selectnew");
select.options.remove(2);//删除第三项
}
删除全部选项
window.οnlοad=function(){
var select=document.getElementById("selectnew");
select.options.length=0;
}
删除选中项
window.οnlοad=function(){
var select=document.getElementById("selectnew");
select.options.remove(select.selectIndex);
}
设置选中项
window.οnlοad=function(){
var select=document.getElementById("selectnew");
select.options[2].selected=true;//设置第三项为选中项
}
获取选中项的文本和值
window.οnlοad=function(){
var select=document.getElementById("selectnew");
var selectvalue=select.options[select.selectIndex].value;
var selecttext=select.options[select.selectIndex].text;
console.log(selectvalue);
console.log(selecttext);
}
获取选中项的值
window.οnlοad=function(){
var select=document.getElementById("selectnew");
var selectvalue=select.value;
//select.text文本拿不到
}
onchange事件
window.οnlοad=function(){
var select=document.getElementById("selectnew");
select.οnchange=function(){
alert(select.selectedIndex);
};
}
修改select某一项的文本和值
window.οnlοad=function(){
var select=document.getElementById("selectnew");
select.options[2]=new Option("文本","值");
}
//单选框
单选框选中项
window.οnlοad=function(){
var oradio=document.getElementsByName("radio");
for(var i=0; i<oradio.length;i++){
if(oradio[i].checked){
return oradio[i].value;
}
}
}
//多选框选中项
window.οnlοad=function(){
var checkboxs=document.getElementsByName("check");
var result="";
for(var i=0; i<checkboxs.length;i++){
if(checkboxs[i].checked){
result+=checkboxs[i].value;
}
}
return result;
}
创建table
function createTable(){
var odiv=document.getElementById("dd");
var table=document.createElement("table");
var row=table.insertRow();
var cell=row.insertCell();
cell.width="150";
cell.style.backgroundColor="#999";
cell.innerHTML="你好吗?";
cell=row.insertCell();
cell.width="200";
cell.style.backgroundColor="#123";
cell.innerHTML="111";
odiv.appendChild(table);
}
修改table