[英]How can I create a randomizer in javascript which will redirect to a random webpage?
我的問題是關於如何為學校項目創建一個旅行目的地生成器(類似於https://travelsp.in/ ),但是我的HTML一直存在重定向到其他網頁的問題。 這是我的js:
var place = ['sydney', 'calgary', 'london'];
function differentPlace() {
var randomNumber= Math.floor(Math.random()*(place.length));
document.getElementById('placeDisplay').innerHTML=place[randomNumber];
}
if (placeDisplay=="calgary") {
return window.location.href = "http://ide50-w.cs50.io:8080/calgary";
}
else if (placeDisplay=="london") {
return window.location.href = "http://ide50-w.cs50.io:8080/london";
}
else if (placeDisplay=="sydney") {
return window.location.href = "http://ide50-w.cs50.io:8080/sydney";
}
和我的HTML是:
<body>
<h2>Discover a new destination:</h2>
<div id="placeDisplay">
</div>
<button onclick="differentPlace()">Find your next journey!</button>
<script src="javascript.js"></script>
</body>
這是一個示例:
var Places = ["place1", "place2", "place3"];
function redirectRandomly() {
let myPlace = Places[Math.random() * (Places.length)];
window.location.href = "http://ide50-w.cs50.io:8080/" + myPlace;
}
好吧,您的代碼有些混亂,請嘗試:
let place = ['sydney', 'calgary', 'london'];
function differentPlace() {
let randomNumber= Math.random() * (Places.length);
let randomPlace = place[randomNumber];
document.getElementById('placeDisplay').innerHTML= randomPlace;
return window.location.href = `http://ide50-w.cs50.io:8080/${randomPlace}`;
}
單擊時,唯一要執行的是函數內部的內容,因此根本不會執行ifs語句,只有在加載頁面時才執行,而不是單擊按鈕時才執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.