用javascript创建基本按钮

时间:2019-01-13 01:34:02

标签: javascript

我正在制作一个按钮,每次单击都会从“您”>“哇”>“旅行”改变。

但是会显示“未捕获的TypeError:onoff不是HTMLInputElement.onclick(7.html:15)的函数”错误

您能帮我解决这个问题吗?

function onoff() {
  currentvalue = document.getElementById('onoff').value;
  
  if (currentvalue == "you") {
    document.getElementById('onoff').value = "wow";
  } else if (currentvalue == "wow";) {
    document.getElementById('onoff').value = "travel";
  } else {
    document.getElementById('onoff').value = "you";
  }
}
<input type="button" value="you" id="onoff" onclick="onoff();">

2 个答案:

答案 0 :(得分:3)

function onoff() {
  var currentvalue = document.getElementById('onoff').value;
  if (currentvalue == "you") {
    document.getElementById('onoff').value = "wow";
  } else if (currentvalue == "wow") {
    document.getElementById('onoff').value = "travel";
  } else {
    document.getElementById('onoff').value = "you";
  }
}
<input type="button" value="you" id="onoff" onclick="onoff()">

完成,一切都在工作:

我已经替换了onclick="onoff();"else if (currentvalue == "wow";)

问题仅出在语法错字

答案 1 :(得分:1)

您的javascript函数未声明,因为其中有错字。 另外,我还建议将要迭代的单词放入数组中,这使代码更易于扩展或修改。它还提高了可读性。

var words = ["you", "wow", "travel"];
var button = document.getElementById('button');
var index = 0;

button.value = words[index++];

function onoff() {
  button.value = words[index++ % words.length];
}
<input type="button" id="button" onclick="onoff()" />