【问题标题】:Is there a way to prefill options in a dropdown in javascript prompt?有没有办法在 javascript 提示符的下拉列表中预填充选项?
【发布时间】:2022-12-31 08:30:29
【问题描述】:

我正在试验 JavaScript(我的代码可以在下面看到)。

我只是想知道是否有办法让提示成为用户可以选择的设置选项的下拉列表,以便我可以保证他们的选择始终是正确的拼写?

// Declare variables
let gameOptions = ['rock', 'paper', 'scissors']
let cpuChoice = '';
let userChoice = '';
let cpuPoints = 0;
let userPoints = 0;
let output = '';

// While loop until either CPU or User reaches 3 points
while (userPoints < 3 && cpuPoints < 3){
  // CPU makes a choice
  cpuChoice = gameOptions[Math.floor(Math.random() * gameOptions.length)];
  // User makes a choice CAN I MAKE A DROPDOWN HERE SO THAT I DON'T NEED THE WHILE LOOP BELOW?
  userChoice = prompt('What is your choice? Enter rock, paper or scissors.');
  // While loop if user enters choice incorrectly
  while (userChoice !== 'rock' && 
          userChoice !== 'paper' && 
          userChoice !== 'scissors') {
  userChoice = prompt('Make sure you enter your choice correctly: Enter rock, paper or scissors.');
  }

  // Check whether user wins the round
  if((userChoice === 'rock' && cpuChoice === 'scissors') ||
      (userChoice === 'scissors' && cpuChoice === 'paper') ||
      (userChoice === 'paper' && cpuChoice === 'rock')) {
        // Add 1 to the user's current score
        userPoints ++;
        alert('Congratulations, you won that round!');
  }
  // No points awarded as it was a tie
  else if (userChoice === cpuChoice) {
    alert('That was a tie!');
  }
  // Add 1 to cpu's current score
  else {
    cpuPoints ++;
    alert('Ouch, you lost that round!');
  }
}

// Create post-game output
if(cpuPoints > userPoints) {
  output = `Unlucky. The game has ended. Computer scored ${cpuPoints}, you scored ${userPoints}`;
}
else {
  output = `Congratulations. The game has ended. Computer scored ${cpuPoints}, you scored ${userPoints}`;
}

// Display output as alert
alert(output);

【问题讨论】:

  • 不,没有办法。通常自定义对话框是使用 html 和 css 创建的

标签: javascript javascript-objects


【解决方案1】:

您已经有了一组可用选项 gameOptions,因此您可以使用 !gameOptions.includes(userChoice) 检查 gameOptions 中是否不存在 userChoice。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-28
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多