首页 > 语言 > JavaScript > 正文

JavaScript关于select的相关操作说明

2024-05-06 14:11:52
字体:
来源:转载
供稿:网友
一、 插入option
1、DOM方法
var oSelectYear = document.getElementById("SelectYear");
var op = document.createElement("option");
op.innerHTML = "2010";
op.value = "2010";
oSelectYear.appendChild(op);

2、new Option方法
var oSelectMonth = document.getElementById("SelectMonth");
oSelectMonth.options.add(new Option(1, 1));
oSelectMonth.options.add(new Option(2, 2));

二、 清空option
var oSelectMonth = document.getElementById("SelectMonth");
oSelectMonth.options.length = 0; //清空Select里面的options

三、 设置默认选中option
var oSelectMonth = document.getElementById("SelectMonth");
//oSelectMonth.selectedIndex = 1; //方法一:默认选中第二项
//setTimeout(function() { oSelectMonth.selectedIndex = 1; }, 0); //用setTimeout延迟是为了防止dom渲染问题
// oSelectMonth.options[1].selected = true; //方法二
oSelectMonth.options[1].setAttribute("selected", "true"); //方法三:比较推荐的用setAttribute来设置
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选