使用javascript或jQuery清除IE中的选定选项

Clear selected option in IE with javascript or jQuery

本文关键字:选项 IE javascript jQuery 清除 使用      更新时间:2023-09-26

想象一下这个HTML代码

<html>
<head>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function clear_form() {
  $("select#block_id").find("option").removeAttr("selected");
}
</script>
</head>
<body>
<form>
<select id="block_id" name="block_id">
<option value=""></option>
<option value="1">1 Peach Road</option>
<option value="2" selected="selected">Bethnal Green Estate</option>
<option value="3">Ley Street</option>
<option value="4">Ogilby Street</option>
</select>
<input type="reset" onclick="clear_form()" value="Clear"/>
<input type="submit"/>
</form>
</html>

当您在Firefox中打开此页面时,按下"清除"按钮将重置所选选项。但这在IE中不起作用,浏览器不会引发任何错误,但什么都不做所选的选项仍然显示。问题是因为我们有'option value="2"selected="selected"'html代码,看起来IE不会清除此选择,它总是出现在页面上。获得本地javascript或jQuery 1.5.2解决方案将是一件很棒的事情。有什么建议吗?

您可以使用JavaScript将select重置为指向其第一个option元素。

使用jQuery。。。

$('#block_id').prop('selectedIndex', 0);

没有。。。

document.getElementById('block_id').selectedIndex = 0;

似乎重置按钮是它在IE中恢复值的原因。

重置按钮将所有表单字段重置为初始值

在您的情况下,最初选择了选项2,因此保留了该值。

  1. 将按钮类型更改为按钮,而不是重置
  2. 如Alex帖子中所述更改clear函数。

    document.getElementById('block_id').selectedIndex = 0;