如何根据从另一个数组打印到文本区域的对象从数组中获取对象



我正试图为博物馆网站制作一个简单的游戏,根据1900家酒店的数据集,告诉你可能住在哪个城市,以及你可能拥有什么酒店。我想让城市按钮调用一个随机城市,该城市打印到一个文本区域,然后根据该文本区域的值,让酒店按钮从该城市的酒店阵列中调用一家随机酒店。请看下面我的尝试,谢谢!

<script> var City = Array(
"Nambour","Adavale",) 
function randomCity() {
var randomCity = City[Math.floor(Math.random() * City.length)];
document.getElementById('randomCity').value = randomCity;
}
var NambourHotel = Array(
"Millchester",
"Carrington ",
"Royal",
"Ellendean",
)
function randomNambourHotel() {
var randomNambourHotel = NambourHotel[Math.floor(Math.random() *NambourHotel.length)];
document.getElementById('randomNambourHotel').value = randomNambourHotel;
}
document.getElementByClass('hotel_button').onkeyup = function() {
var text_value = document.getElementById('randomCity').value;
if (text_value.includes("Nambour") === true) {
randomNambourHotel();
} else {}
}
</script>
<button class="city_button" type="randomCity"   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="randomNambourHotel">WHAT HOTEL MIGHT YOU HAVE OWNED?</button>
<div class="hotel_output">
<div id="hotels_wrap">
<textarea name="randomNambourHotel" id="randomNambourHotel" style="resize: none;"></textarea>
</div>
</div>

https://jsfiddle.net/arkatark/L9yxzbd1/2/

请检查此解决方案。我为每个城市添加了酒店阵列,当点击酒店按钮时,所选城市酒店中的一家随机酒店将被填充。

var City = Array(
"Nambour",
"Adavale",
)
function randomCity() {
var randomCity = City[Math.floor(Math.random() * City.length)];
document.getElementById('randomCity').value = randomCity;
document.getElementById('randomNambourHotel').value = "";
}
var NambourHotel = {'Nambour' : [
"Millchester",
"Carrington ",
"Royal",
"Ellendean",
],
'Adavale': [
"Millchester-a",
"Carrington-a",
"Royal-a",
"Ellendean-a",
]
}
function randomNambourHotel() {
var city = document.getElementById('randomCity').value;
var hotelsInselectedCity = NambourHotel[city]
var randomNambourHotel = hotelsInselectedCity[Math.floor(Math.random() * hotelsInselectedCity.length)];
document.getElementById('randomNambourHotel').value = randomNambourHotel;
}

https://jsfiddle.net/31xzd680/

最新更新