javascript - 如何在javascript中通过第二次点击和第三次点击添加另一个事件?
问题描述
经过几个小时的反复试验,我把我的帖子放在这里,问了一个问题,也许你们中的一个人可以帮助我。我创建了一个在单击按钮后使用“onclick”属性调用的函数。此功能更改页面选定元素的字体大小。我想添加一个不同的百分比,例如第二次单击按钮时为 200%。我会很感激任何帮助。
JS代码:
document.getElementsByClassName("increase-size").addEventListener("click", increasSize);
function increasSize() {
var x = document.querySelectorAll("h1, h2, h3, h4, h5, h6, p, input, a");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.fontSize = "150%";
}
}
HTML 代码:
<button type="button" class="increase-size" onclick="increasSize()"></button>
我试图用计数器解决它,但我失败了。
document.getElementsByClassName("increase-size").addEventListener("click", increaseSize);
var counter = 0;
function increaseSize() {
counter += 1;
var x = document.querySelector("html");
var i;
for (i = 0; i < x.length; i++) {
if(counter == 1) {
x[i].style.fontSize = "150%";
} else if (counter == 2) {
x[i].style.fontSize = "200%";
}
}
}
解决方案
您的代码有几个问题:
increase-size
应该是 theid
而不是 theclass
并且称为 asdocument.getElementById("increase-size")
。否则,您可以使用它,document.getElementsByClassName("increase-size")[0]
因为它返回元素列表。- 该
click
函数应仅传递function
名称,否则将被调用两次:
<button type="button" class="increase-size" onclick="increasSize"></button>
counter
应该是一个全局变量,并且incremented
在每次调用中。每次使用该函数时,此处的使用方式都设置为零。- 您不需要
for loop
. - 最好不要在函数名中出现拼写错误:将其重命名为
increaseSize
. - 您只需在
html
或中设置一次侦听器JavaScript
。最好留下js
零件。
最终解决方案如下:
document.getElementById("increase-size").addEventListener("click", increaseSize);
let counter = 0;
function increaseSize() {
console.log(counter);
counter++;
var x = document.querySelector("html");
if(counter == 1) {
x.style.fontSize = "150%";
} else if (counter == 2) {
x.style.fontSize = "200%";
}
}
<html>
<button type="button" id="increase-size">Increase</button>
<h1>Hello</h1>
<h2>World</h2>
</html>
推荐阅读
- java - 如何在简单的 Spring Boot 应用程序中自动装配扩展 CrudRepository 的存储库?
- ios - 为什么@EnvironmentObject 强制重新初始化视图?
- hyperledger-fabric - 如何将外部数据资源集成到 Hyperledger Fabric 中?
- excel - 如何在 Excel 中的 IF/AND 函数中使用 MONTH() 函数
- c# - 将数据表转换为 JSON 并逐行发布到 PubSub
- c++ - Clang-Tidy 关于未能初始化匿名联合的所有字段的警告是误报吗?
- asp.net - TextChanged 事件在焦点从该文本框(telerik 文本框)更改之前不会触发
- regex - RegEx 将最后一项与 Breakline 匹配
- python - 用循环中的行填充现有数据框
- python - 使用 twilio 调用时,PORT 80 突然不起作用