我遇到了jQuery的问题。我试图创建一个由按下的单个键触发的偶数,但相反 - 它的一些 - 由任何键触发。不明白为什么。我做了很多次,没有问题。突然间,这种特殊的代码组合表现得很奇怪。我不明白。我已经尝试了各种各样的实验来弄明白。问题在多个浏览器上非常具体和一致。请帮忙!这是该页面的链接。 http://www.lyliansill.com/test.html> 看看我在谈论什么,按' a'它的工作原理应该如此。重新加载并按下任何其他键,仍然会触发一半事件。
<!DOCTYPE html PUBLIC "-//W3C/DTD/ XHTML 1.0 Strict/EN" "http://www.w3.org/TR/xhtml1/dtd/xhtml1-strict.dtd">
<!-- This file is on level 02 -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Test</title>
<style type="text/css">
.hidden
{
display: none;
}
.select
{
color:#cc0000;
}
</style>
</head>
<body>
<h1 class="test hidden">Test</h1>
<script type="text/javascript" src="playground/libraries/jquery.js">
</script>
<script type="text/javascript">
function showIt()
{
$(".showIt").show();
}
$(document).keypress
(
function(e)
{
if (e.which === 97)
$(".test").addClass("select"); // this line works like it should
$(".test").addClass("showIt"); // these two lines are activated...
showIt(); // ...by pressing any key! why??
}
);
</script>
</body>
</html>
答案 0 :(得分:1)
这就是为什么你应该确保使用括号,让我们看一下代码:
if (e.which === 97)
$(".test").addClass("select"); // this line works like it should
$(".test").addClass("showIt"); // these two lines are activated...
showIt(); // ...by pressing any key! why??
注意if语句没有括号:if(){ ... }
,所以只有当if语句为真时才执行下面的行,但其余的不在if语句中:
$(".test").addClass("showIt"); // these two lines are activated...
showIt(); // ...by pressing any key! why??
始终运行。要解决此问题,请添加括号:
if (e.which === 97) {
$(".test").addClass("select"); // this line works like it should
$(".test").addClass("showIt"); // these two lines are activated...
showIt(); // ...by pressing any key! why??
}
答案 1 :(得分:0)
这是如何修复它(添加大括号):
function(e)
{
if (e.which === 97) {
$(".test").addClass("select"); // this line works like it should
$(".test").addClass("showIt"); // these two lines are activated...
showIt();
} // ...by pressing any key! why??
}
$(".test").addClass("showIt"); // these two lines are activated...
showIt();
} // ...by pressing any key! why??
}