OnClick 事件在我加载页面时被调用

the onclick event gets invoked when i load the page

本文关键字:调用 加载 事件 OnClick      更新时间:2023-09-26

无法理解为什么当我运行文件时调用onclick事件,而当我单击div时应该调用它。

法典:

<html>
<head>
<link rel="Stylesheet" type="text/css" href="shoppingcart.css">
</head>
<script type="text/javascript">
var count=0;
function swap()//cannot understand why it is running on loading the page
{
  if(count==0)
  {
    document.getElementById('log').style.display='none';
    count++;
   }
   else
   {
   document.getElementById('log').style.display='block';
   count=0;
   }
}
</script>
<body>
<div onclick="swap()" style="padding-left:30px;height:100px;width:300px;float:left;margin-right:180px"  >
<h1 style="center">LOG IN</h1>
</div>
<div id="log" class="block border goudystout">
Email:<input type="email"/>
Password:<input type="password"/>
</div>
</body>
</html>

胡乱猜测。您正在将swap()设置为您的div 单击处理程序,而不是swap,因此它在页面加载时执行。

首先,您将脚本部分放在正文头部部分之间,它应该在正文部分。这可能是它无法按预期工作的主要原因。

根据这篇文章:http://www.simplehtmlguide.com/javascript.php...

调用中使用括号是合法的,您可以尝试在它后面加上分号,但 javascript 应该处理自动分号插入。

代码对我来说很好用

这意味着你的css文件中有一个问题,也许display:block!important; 对于.block类

<div id="log" class="block border goudystout">

这破坏了你的代码

解决它!