以下 html 代码在 Firefox 中有效,但由于某种原因在 IE 中失败(Label2 未显示)。这是一个错误还是我错过了什么?
如有任何帮助,我们将不胜感激。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript">
</script>
<script>
jQuery(document).ready(function(){
function setVis(){
var val = $("#check").is(":checked");
if (val)
$("#g_1").show();
else
$("#g_1").hide();
}
setVis();
$("#check").change(setVis);
});
</script>
</head>
<body>
<span>
<input type="checkbox" id="check" />
<label>Label1</label>
</span>
<span id="g_1">
<label>Label2</label>
</span>
</body>
</html>
最佳答案
原因:
根据 MSDN,change event是
...fired when the contents are committed and not while the value is changing. For example, on a text box, this event is not fired while the user is typing, but rather when the user commits the change by leaving the text box that has focus.
复选框的行为类似:在 IE 中,直到焦点从元素上移除后,事件才会触发(尝试一下:单击复选框,然后按 Tab 键关闭,行为符合预期)。 Firefox 显然不尊重这种区别。
解决方案:
使用click
事件处理程序而不是change
:
$("#check").click(setVis);
...并且跨浏览器的行为应该一致。
关于Internet Explorer 中的 jquery show()/hide() 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/368807/