每次按下按钮时如何创建一个不同的文本?

时间:2015-10-22 03:32:39

标签: javascript html

我如何能够创建一个onclick提供如下内容的按钮:

第一次按下按钮时,文本应更改为“您按下按钮”(无引号)

第二次按下按钮时,文本应更改为“您再次按下按钮”。 (没有引号)

按下按钮的第三到第五次,文本应更改为“您按下按钮n次”。 (没有引号),n代表按下按钮的次数。

如果按下该按钮六次或更多次,则应将文本替换为“停止按下按钮”。 (没有引号)

我完全迷失在这里。有没有办法可以使用if / else语句来完成?看起来很简单但我甚至不知道从哪里开始。谢谢您的帮助。

5 个答案:

答案 0 :(得分:1)

尝试创建包含要显示的文本的数组,如果数组Array.prototype.shift()大于.length,则使用1显示数组中的项目,否则显示数组中的剩余项目

var arr = ["You pushed the button"
           , "You pushed the button (again)."
           , "You pushed the button 3 times."
           , "You pushed the button 4 times."
           , "You pushed the button 5 times."
           , "Stop pushing the button."];

document.querySelector("button").onclick = function() {
  this.innerHTML = arr.length > 1 ? arr.shift() : arr[0]
}
<button>click</button>

答案 1 :(得分:0)

Random.Next(1, sides)
<script>
var i = 0;
$(document).ready(function() {
  $("#button").click(function() {

    i = i + 1;
    switch (i) {
      case 1:
        alert('You pressed the button');
        return;
      case 2:
        alert('You pressed the button Twice ');
        return;
      default:
        alert('You pressed the button ' + i + ' times');
        return;
    }
  });
});</script>

这是代码。

答案 2 :(得分:0)

是的,最简单的方法是简单地将文本值放入数组中,然后从数组中调用文本,例如。或者如果你喜欢satatements,你可以在实现一个计数器整数后使用它们。

var n=0;
var textList=["You Clicked The Button", "You Clicked The Button Again", "You Clicked The Button 3 Times", "You Clicked The Button 4 Times"];

function buttonClick(btn){
    btn.innerHTML=textList[n];
    n++;
  
  
  }

答案 3 :(得分:0)

希望这会有所帮助

<button type = 'button' id ='clickB'>Click me </button>

仅使用javascript

var x = document.getElementById('clickB');
var counter = 1;

x.addEventListener('click',function(){
  if(counter == 1){
    alert('You clicked me');
  }
    else if(counter ==2){
    alert('You clicked me again');
    }
    else{
        alert('You clicked me ' +counter+'times');
    }
    counter++;
},false)

jsfiddle

答案 4 :(得分:0)

您需要跟踪按钮被点击的次数。每次触发点击事件时,clickCount都会增加。每次单击该按钮时,都会根据您想要的范围运行一段代码。

HTML:

<div id="update">You should probably click the button</div>
<input id="button" type="button" value="Click!"/>    

Javascript:

var clickCount = 0;
var update = document.getElementById('update');

document.getElementById('button').onclick = function() {
    clickCount++;
    if(clickCount===1) {
        update.innerHTML = 'You pushed the button';
    } else if(clickCount===2) {
        update.innerHTML = 'You pushed the button again';
    } else if(clickCount>=3 && clickCount<=5) {
        update.innerHTML = `You pushed the button ${clickCount} times`;
    } else if(clickCount>6) {
        update.innerHTML = 'Stop pushing the button';
    }
};

行动准则:

这是demo