javascript - 页面加载时自动按下按钮
问题描述
我是初学者,我正在学习 JavaScript。我正在尝试制作密码生成器。我在 HTML 第 29 行和第 33 行有两个按钮。当我加载页面时,这两个按钮会自动按下,以后无法按下。我不明白为什么会这样!
下面是我的代码:
const minusEl = document.getElementById('minus');
const plusEl = document.getElementById('plus');
const passwordLengthEl = document.getElementById('password-length');
// Password Length
function passwordLengthChose(value) {
const passwordLength = parseInt(passwordLengthEl.innerText) + value;
passwordLengthEl.innerText = passwordLength;
console.log(passwordLength);
console.log("clickd");
}
minusEl.addEventListener('click', passwordLengthChose(-1));
plusEl.addEventListener('click', passwordLengthChose(1));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Password Generator - Avast Clone by Dabananda Mitra</title>
<!-- FontAwesome Icon CDN -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
<!-- Custom CSS -->
<link rel="stylesheet" href="https://res.cloudinary.com/djz3p8sux/raw/upload/v1631537358/StackOverflow/main_mjkv8p.css">
</head>
<body>
<!-- Title -->
<h1>Random Password Generator</h1>
<!-- Main Markup -->
<main>
<section id="password-generator-box">
<input type="text" id="password-display">
<button type="button" id="regenerate-password">
<i class="fas fa-sync"></i>
</button>
<button type="button" id="copy">COPY</button>
</section>
<section id="password-length-box">
<h3>Password legnth: </h3>
<div id="password-length-section">
<button id="minus" type="button">
<i class="fas fa-minus"></i>
</button>
<span id="password-length">8</span>
<button id="plus" type="button">
<i class="fas fa-plus"></i>
</button>
</div>
</section>
</main>
<!-- Custom JavaScript -->
<script src="./javascripts/theme.js"></script>
<script src="./javascripts/password-generator.js"></script>
</body>
</html>
请帮助我为什么会发生这种情况,我该如何解决?
解决方案
代替:
minusEl.addEventListener('click', passwordLengthChose(-1));
plusEl.addEventListener('click', passwordLengthChose(1));
和:
minusEl.addEventListener('click', () => passwordLengthChose(-1));
plusEl.addEventListener('click', () => passwordLengthChose(1));
在您的代码中,您在注册事件侦听器时调用了这些函数。您需要传递一个函数。
推荐阅读
- html - 图像重定向居中
- git - GitHub 不允许我上传大文件
- opengl - 通用三角形网格的简单纹理映射
- json - 如何使用 jq 对 json 进行分组,然后转换为 yaml
- excel - 当值绑定到 Excel 或 Access 中的 vbNewLine 时,如何比较 VBA 中的两个值
- svg - 需要在 Xamarin 中的图像上显示 svg
- java - 我的添加请求中出现的参数比我需要填写的要多
- r - 对数据集排序,以便 geom_path() 以与人眼相同的方式连接点
- python - pypoetry 可以只安装我要求它添加的依赖项吗?
- java - 有没有一种方法可以强制用户将 POST/PUT 请求中的特定字段排除到控制器级别的 API 端点?(科特林/Java/REST)