首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何让提示符读取文本输入和打印定制的文本信息?

问如何让提示符读取文本输入和打印定制的文本信息?
EN

Stack Overflow用户
提问于 2022-03-22 07:23:06
回答 1查看 251关注 0票数 0

我试着用基本的JS做一个文字冒险游戏。基本上,用户将有两个选项,提示框应该根据用户的选择打印相应的消息。

我猜缺少的是一个事件侦听器--但我不知道如何实现它。

​

代码语言:javascript
复制
let message = prompt("Hi this is an adventure. Select your input as A or B. In front of you there is a sign. Pick  A. Forest B. Lake")

if (A) {
  prompt("you see the bushes ahead of you rustling.You-- A.proceed ahead  B.turn back and run")
};
else if (B) {
  prompt("you see the water bubbling. You--A. walk up B.--flee")
}

​

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-22 08:11:27

您需要比较if (message.toUpperCase() === "A") {以允许用户键入a或A

如果使用对象和窗体,代码也会少得多。

​

代码语言:javascript
复制
const advent = {
  "Start": {
    "text": "Hi this is an adventure. Click the buttons to make your choice. In front of you there is a sign. You go direction",
    "a": "Forest",
    "b": "Lake"
  },
  "Forest": {
    "text": "you see the bushes ahead of you rustling. You --",
    "a": "proceed ahead",
    "b": "turn back and run"

  },
  "Lake": {
    "text": "you see the water bubbling. You--",
    "a": "walk up",
    "b": "flee"
  },
  "walk up": {
    "text": "You drown; The end"
  },
  "flee": {
    "text": "You fall in a hole and die; The end"
  }
};

let currentPath = advent["Start"]

window.addEventListener("DOMContentLoaded", function() {
  const text = document.getElementById("text");
  const A = document.getElementById("a");
  const B = document.getElementById("b");
  const show = () => {
    text.innerHTML = currentPath.text; console.log(currentPath.a)
    if(currentPath.a) A.value = currentPath.a
    if(currentPath.b) B.value = currentPath.b
  };

  const form = document.getElementById("myForm").addEventListener("click", function(e) {
    const tgt = e.target;
    currentPath = advent[currentPath[tgt.id]]
    document.getElementById("choices").hidden = (!currentPath.a && !currentPath.b); // hide if no choices
    show()
  });
  show(); // start
});
代码语言:javascript
复制
<form id="myForm">
  <div id="text"></div>
  <div id="choices"><input type="button" id="a" value="A"> <input type="button" id="b" value="B"></div>
</form>

​

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71568239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档