创建一个包含提示的网页

时间:2017-08-31 23:48:26

标签: javascript loops prompt

我的提示框不起作用?从那以后我就把元素放进去了。

我需要提示框,以便我可以输入信息,然后该信息自动进入表格,然后通过在表格行中有*来自动读取最大数量的$。我不是100%的js编码所以不要笑如果它是一个简单的修复(这是简单的事情,让我)。

这是我的代码,我不知道我做错了什么

“我的桌子在脑袋里”

function money(){

this.currency = "";
this.amount = "";
this.exchangeRate = "";
this.ausDollars = "";

tbody = document.getElementsByTagName('tbody')[0];
for (var i = 0; i <= 3; i++) 
  trElement = document.createElement('tr');
  tbody.appendChild(trElement);

// Read the 3 letter currency abbreviation entered
  currency = prompt('Please enter a 3-letter currency abbreviation', +i, "");
  // If the input data is invalid ask the user to re-enter it
  while (currency.length != 3) {
    currency = prompt('Currency abbreviation was not entered', "");
    currency = parseFloat(currency);
  }

currencyTH = document.createElement('th');
  currencyText = document.createTextNode(currency);
  currencyTH.appendChild(currencyText);
  trElement.appendChild(currencyTH);

 // Read the amount and convert it to entered currency 
  amount = prompt('Please enter an amount of money in that currency', +i, "");
  // If the input data is invalid ask the user to re-enter it
  while (isNaN(amount) || amount < 0) {
    amount = prompt('An amount of money was not entered')
    amount = parseFloat(amount);
  }

amountTH = document.createElement('th');
  amountText = document.createTextNode(amount);
  amountTH.appendChild(amountText);
  trElement.appendChild(amountTH);

 exchangeRateTH = document.createElement('th');
  exchangeRateText = document.createTextNode(exchangeRate);
  exchangeRateTH.appendChild(exchangeRateText);
  trElement.appendChild(exchangeRateTH);

}

1 个答案:

答案 0 :(得分:1)

问题是您使用 prompt() 来提示用户输入显示与用户输入相关的错误消息。为此,您正在寻找 alert()

首先,您在提示中设置货币:

currency = prompt('Please enter a 3-letter currency abbreviation', +i, "");

然后你跑:

 currency = prompt('Currency abbreviation was not entered', "");

会覆盖最初存储在currency中的值,因此您无法在下一行上运行parseFloat()

 currency = parseFloat(currency);

要解决此问题,请使用:

alert('Currency abbreviation was not entered');

请注意,这与amount的情况相同。而不是:

amount = prompt('An amount of money was not entered');

使用:

alert('An amount of money was not entered');

另请注意,您的while循环结构在无限期提示之前略有错误,直到达到正确的值。您应该在循环外部设置变量,然后检查条件,而不是最初提示然后运行while循环。并且parseFloat() 必须超出while循环,否则您将陷入无限循环!

var currency = '';
currency = prompt("Please enter 3 characters");
while (currency.length != 3) {
  alert('Currency must be three characters');
  currency = prompt("Please enter 3 characters");
}
currency = parseFloat(currency);

console.log("The stored value was: " + currency);

希望这有帮助! :)