gpt4 book ai didi

javascript - jquery 按键条件使任意键出现故障

转载 作者:行者123 更新时间:2023-11-28 01:00:29 25 4
gpt4 key购买 nike

我在使用 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>

最佳答案

这就是为什么你应该确保使用括号,让我们看一下代码:

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 语句为 true 时才会执行 is 下的行,但其余部分不在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??
}

关于javascript - jquery 按键条件使任意键出现故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25676622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com