You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据文本框中随机生成的城市获取对应酒店数组元素?

问题分析与解决方案

你的代码存在几个关键问题导致功能无法正常工作,以下是问题点和修复后的完整实现:

主要问题点

  • 事件绑定错误:使用了不存在的document.getElementByClass(正确写法是document.getElementsByClassName),且给按钮绑定了onkeyup事件(按钮交互应使用onclick)
  • 数据结构不灵活:每个城市单独定义数组,后续新增城市时代码扩展性差
  • 未覆盖多城市逻辑:仅处理了Nambour的酒店生成,未适配Adavale的情况
  • 按钮属性错误:按钮的type属性应为button,而非函数名称
  • 语法冗余:数组定义使用Array()不如直接用[]简洁,且末尾逗号可能引发兼容问题

修复后的完整代码

<button class="city_button" type="button" onclick="randomCity()">WHAT REGION MIGHT YOU HAVE LIVED IN?</button>

<div class="city_output">
  <div id="city_wrap">
    <textarea name="randomCity" id="randomCity" style="resize: none;"></textarea>
  </div>
</div>

<button class="hotel_button" type="button">WHAT HOTEL MIGHT YOU HAVE OWNED?</button>

<div class="hotel_output">
  <div id="hotels_wrap">
    <textarea name="randomHotel" id="randomHotel" style="resize: none;"></textarea>
  </div>
</div>

<script>
// 用对象统一管理城市与酒店的映射关系,方便扩展
const cityHotels = {
  "Nambour": ["Millchester", "Carrington", "Royal", "Ellendean"],
  "Adavale": ["Central Hotel", "Outback Lodge", "Desert Inn"] // 可自行替换为Adavale真实酒店数据
};

// 获取所有城市名称
const cities = Object.keys(cityHotels);

function randomCity() {
  // 随机选取城市
  const randomCity = cities[Math.floor(Math.random() * cities.length)];
  document.getElementById('randomCity').value = randomCity;
}

function randomHotel(selectedCity) {
  // 根据城市获取对应的酒店数组,随机选取一个
  const hotels = cityHotels[selectedCity];
  const randomHotel = hotels[Math.floor(Math.random() * hotels.length)];
  document.getElementById('randomHotel').value = randomHotel;
}

// 给酒店按钮绑定点击事件
document.getElementsByClassName('hotel_button')[0].onclick = function() {
  const selectedCity = document.getElementById('randomCity').value.trim();
  
  // 检查选中的城市是否在我们的酒店数据中
  if (cityHotels[selectedCity]) {
    randomHotel(selectedCity);
  } else {
    // 若未选择城市或城市无对应数据,提示用户
    document.getElementById('randomHotel').value = "请先选择一个有效城市";
  }
};
</script>

关键修改说明

  1. 优化数据结构:使用cityHotels对象关联城市与对应酒店数组,后续新增城市只需补充键值对即可
  2. 修正事件绑定:使用getElementsByClassName获取酒店按钮并绑定onclick事件,确保点击触发逻辑
  3. 完善多城市支持:随机城市逻辑自动适配所有已定义城市,酒店选取根据选中城市动态匹配对应数组
  4. 增强用户体验:添加未选择城市或无效城市时的提示文本
  5. 简化语法:使用更简洁的数组/对象字面量定义数据,移除冗余逗号

内容的提问来源于stack exchange,提问作者Amelia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 12:30:56