首页 > 解决方案 > 如何在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%";
    }
  }
}

标签: javascripthtmlcss

解决方案


您的代码有几个问题:

  1. increase-size应该是 theid而不是 theclass并且称为 as document.getElementById("increase-size")。否则,您可以使用它,document.getElementsByClassName("increase-size")[0]因为它返回元素列表。
  2. click函数应仅传递function名称,否则将被调用两次:
<button type="button" class="increase-size" onclick="increasSize"></button>
  1. counter应该是一个全局变量,并且incremented在每次调用中。每次使用该函数时,此处的使用方式都设置为零。
  2. 您不需要for loop.
  3. 最好不要在函数名中出现拼写错误:将其重命名为increaseSize.
  4. 您只需在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>


推荐阅读