Javascript循环和最终警报,FOR或WHILE?

时间:2016-04-21 01:26:53

标签: javascript jquery loops for-loop while-loop

新手编程,这是我练习的代码,我无法弄清楚如何编写我的概念,我不确定是否需要使用forwhile来满足以下要求:

  

在3或5次用户未能在提示框中输入内容后,最终警报会显示出“没有更多机会!”之类的内容。然后将div背景变为灰色。

欢迎任何帮助以帮助我改进。

JS

var mObjt = {
    userInput: "",

    setInput: function(){
        document.getElementById("div1").innerHTML = mObjt.userInput;
    },

    conRequest: function(){
        if(mObjt.userInput != ""){
            mObjt.setInput();
        } else {
            alert("There is no input!");
            mObjt.popRequest();
        }
    },

    popRequest: function(){ 
        mObjt.userInput = prompt("Enter a word:");
        mObjt.conRequest();
    }
}

HTML:

<div id="div1" style="width:200px; height:30px; border:1px solid;"></div>
<button type="button" onClick="mObjt.popRequest()">Add Property</button>

1 个答案:

答案 0 :(得分:0)

你不应该使用任何类型的循环。保持计数器变量。每次用户失败时,请增加计数器。当计数器达到5时,做任何需要做的事情。

var failCount = 0;

function handleInput() {
  // This is a totally fake example just to show you want to do
  if(input) {
    // Input valid, yay
  } else {
    // Input invalid
    failCount++;
    if(failCount >= 5) {
      // Disable your stuff
      alert('Oh no, input failed: you have no more remaining attempts');
    } else {
      alert('Oh no, input failed');
    }
  }
}