为什么我不能在onclick函数中添加计数?

时间:2019-09-19 13:35:38

标签: javascript css onclick

我想尝试使用计数来更改点击行为。我所有其他条件都起作用,但是我不明白为什么我的计数条件不起作用。有谁知道我能做些什么来使其工作?

对于我尝试的计数-(this.count == 2),(count == 2)和(uh.count == 2)

function uh() {
  var words;
  var conf = confirm("ooh that felt goood");
  var button = document.querySelector("#selector");
  var box =
    document.querySelector("#box");
  var count = 0;
  if (this.count == 5) {
    button.classname = "button3";
    words = " ";
  } else if (this.count == 4) {
    button.classname = "button3";
    words = "I give up. This is all you get.";
    count++;
  } else if (this.count == 3) {
    button.classname = "button3";
    words = "...";
    count++;
  } else if (this.count == 2) {
    button.className = "button2";
    words = "the power?";
    count++;
  } else if (button.className == "button3") {
    button.className = "button2";
    words = "ahahaha... ha.. uh..";
    count++;
  } else if (button.className == "button2") {
    button.className = "button3";
    box.className = "box";
    words = "THE POWER";
  } else if (conf == true) {
    words = "AHAHAHA I HAVE YOU NOW";
    button.className = "button2";
  } else {
    words = "...";
    button.className = "button";
  }
  document.querySelector(".header").innerHTML = words;
}
body {
  background-color: black;
}

#header {
  text-align: center;
}

.header {
  background-color: #000099;
  color: white;
  display: inline-block;
  border: 5px solid white;
  padding: 20px;
  width: 90%;
}

#box {
  text-align: center;
  background-color: green;
  height: 500px;
}

.box {
  text-align: center;
  height: 500px;
}

.button {
  background-color: grey;
  color: white;
  margin: 170px;
  text-decoration: none;
  display: inline-block;
  font-size: 20px;
}

.button2 {
  background-color: #ff0000;
  border: none;
  color: white;
  padding: 15px 32px;
  margin: 170px;
  text-decoration: none;
  display: inline-block;
  font-size: 40px;
  box-shadow: 0px 0px 10px white;
}

.button3 {
  background-color: black;
  border: none;
  color: red;
  padding: 30px 60px;
  margin: 170px;
  text-decoration: none;
  display: inline-block;
  font-size: 60px;
  box-shadow: 0px 0px 20px 5px gold;
}
<div id=h eader>
  <h1 class="header"> I feel an itch...
    <h1>
</div>
<div id="box">
  <input type="button" id="selector" class="button" value="CLICK ME" onclick="uh()">
</div>

1 个答案:

答案 0 :(得分:1)

每次调用count时都会声明并重新初始化

uh()。变量生存期在函数结束时结束,因此无法在多次调用uh()时保留其值。

您可以做的是声明一个名为count的对象,该对象具有相同的名称属性,并且在该对象上声明call() uh。然后this将引用对象uh(),因此this.count在同一对象的多次调用中将具有可转移的值。

var count = {count: 0};

console.log(count.count);//0

up.call(count);

function up() {

this.count++;
//... here add any kind of check on the value of count
}

console.log(count.count);//1