JScript:怎么样写一个Onclick事件,使得下拉菜单的某一项被选中?
JScript:怎么样写一个Onclick事件,使得下拉菜单的某一项被选中?比如<formname=f1><selectname=s><optionid=s1value=...
JScript:怎么样写一个Onclick事件,使得下拉菜单的某一项被选中?
比如
<form name=f1>
<select name=s><option id=s1 value=s1>选项1</option>
<option id=s2 value=s2>选项2</option>
<option id=s3 value=s3>选项3</option>
<input type=button value="选择第二个" onclick="??">
</form>
<form name=f2>
<select name=s><option id=s1 value=s1>选项1</option>
<option id=s2 value=s2>选项2</option>
<option id=s3 value=s3>选项3</option>
<input type=button value="选择第二个" onclick="document.f2.s.value='s2';document.f2.s+='<option value=s2>第二项</option>';">
</form>
这样虽然好了,但是出错。 展开
比如
<form name=f1>
<select name=s><option id=s1 value=s1>选项1</option>
<option id=s2 value=s2>选项2</option>
<option id=s3 value=s3>选项3</option>
<input type=button value="选择第二个" onclick="??">
</form>
<form name=f2>
<select name=s><option id=s1 value=s1>选项1</option>
<option id=s2 value=s2>选项2</option>
<option id=s3 value=s3>选项3</option>
<input type=button value="选择第二个" onclick="document.f2.s.value='s2';document.f2.s+='<option value=s2>第二项</option>';">
</form>
这样虽然好了,但是出错。 展开
1个回答
展开全部
<HTML>
<HEAD>
<TITLE>SelectItem</TITLE>
<script type="text/javascript">
function selectItem(selectIndex){
//获取select元素对象
var tagSelect = document.getElementById("select1");
//方式一:使用select元素的selectedIndex属性,selectedIndex是设置或获取选中选项(<option>)位于 select 对象中的位置
tagSelect.selectedIndex = selectIndex;
/*方式二:使用select元素的options集合,options代表select元素中的所有<option>子标记,
如果需要访问options集合中的第二个option时,可以通过options[1]的方式访问;
还有tagSelect.options.length可以返回options的个数 */
//tagSelect.options[selectIndex].selected = true;
}
</script>
</HEAD>
<BODY>
<form name="form1">
<select name="select1">
<option id="s1" value="s1">选项1</option>
<option id="s2" value="s2">选项2</option>
<option id="s3" value="s3">选项3</option>
</select>
<input type=button value="选择第二个" onclick="selectItem(1)">
</form>
</BODY>
</HTML>
<HEAD>
<TITLE>SelectItem</TITLE>
<script type="text/javascript">
function selectItem(selectIndex){
//获取select元素对象
var tagSelect = document.getElementById("select1");
//方式一:使用select元素的selectedIndex属性,selectedIndex是设置或获取选中选项(<option>)位于 select 对象中的位置
tagSelect.selectedIndex = selectIndex;
/*方式二:使用select元素的options集合,options代表select元素中的所有<option>子标记,
如果需要访问options集合中的第二个option时,可以通过options[1]的方式访问;
还有tagSelect.options.length可以返回options的个数 */
//tagSelect.options[selectIndex].selected = true;
}
</script>
</HEAD>
<BODY>
<form name="form1">
<select name="select1">
<option id="s1" value="s1">选项1</option>
<option id="s2" value="s2">选项2</option>
<option id="s3" value="s3">选项3</option>
</select>
<input type=button value="选择第二个" onclick="selectItem(1)">
</form>
</BODY>
</HTML>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询