【问题标题】:Javascript loop and final alert, FOR or WHILE?Javascript 循环和最终警报,FOR 还是 WHILE?
【发布时间】:2016-08-13 23:15:36
【问题描述】:

编程新手,这是我的练习代码,我不知道如何编写我的概念,我不确定是否需要使用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>

【问题讨论】:

  • 粗体字是我想要的。
  • 您可以使用 for 或 while 循环,具体取决于您的喜好。但我建议你在问这类问题之前先阅读循环是如何工作的
  • 什么想法,我希望提示框给用户 5 次机会,他失败了,然后是警报,然后 DIV 变灰。

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


【解决方案1】:

您不应该为此使用任何类型的循环。保留一个计数器变量。每次用户失败时,增加计数器。当计数器达到 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');
    }
  }
}

【讨论】:

  • 您假设每次单击按钮时提示应该只出现一次。听起来他希望如果未提供单词,则在单击后提示最多持续 5 次,这需要循环。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-18
  • 1970-01-01
相关资源
最近更新 更多