<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var x = 40
var y = 20
var input
function myFunction() {
var person = prompt("Please enter your name", "Harry Potter");
if (person = "luke") {
document.getElementById("demo").innerHTML =
"Hello " + x + "! How are you today?";
}
}
</script>
我的代码中现在有一个文本框,当您输入任何内容时,它会给您 Hello 40 你今天好吗?我想要的只是当你输入 fire 时它会说这一点,然后如果你输入水或风则发出不同的提示......有人知道该怎么做吗?
最佳答案
根据您的评论反馈,我修改了代码,仅接受您想要接受的答案,并继续提示输入,直到它们与您想要的相匹配。它还修复了一个小故障,无论他们输入什么,都会提示他们最喜欢的水和土:
对于初学者来说,它输出“Hello 40”的原因是因为在您的代码中
`"Hello " + x + "! How are you today?";`
您正在输出存储有 40 的变量。您应该将 x 更改为 person,因为它包含您要输出的名称。至于要求根据输出给出其他提示,只需执行以下操作:
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<p id="demo2"></p>
<script>
function myFunction() {
var element = prompt("Please enter your name", "fire");
var favorite = "";
var testing = 0;
while (testing == 0)
{
if(element == "fire" || element == "water" || element == "earth")
{
testing = 1;
}
else
{
element = prompt("Please enter your favorite element","fire");
}
}
document.getElementById("demo").innerHTML =
"You have chosen " + element + "!";
if (element == "water") {
favorite = prompt("What body of water is your favorite?")
document.getElementById("demo2").innerHTML =
"And your favorite body of water is" + favorite + "!";
}
if (element == "earth") {
favorite = prompt("What formation of earth is your favorite?")
document.getElementById("demo2").innerHTML =
"And your favorite formation of earth is" + favorite + "!";
}
}
</script>
使用您的代码作为模板我构建了这个。我去掉了你没有使用的变量来巩固空间。您可以轻松地复制并粘贴“if”语句并相应地放置它们,以便为用户提供更多选项/提示。如果要隐藏其中一个文本字段,请创建一个条件 (if) 语句并将元素内部 html 的值设置为空字符串 ("")。祝你好运。
关于javascript - 如何限制提示框中可以放入哪些单词,以便为每个单词提供不同的提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26198845/