JavaScript link 导致随机 url

JavaScript link leads to random url

我想知道如何在 HTML css 和 JavaScript 中创建指向三个随机 URL 之一的 link。示例:当您单击 link 时,它将随机引导您到 hi.html、hi2.html 或 hi3.html。我将如何做到这一点?

您可以将所有三个 url 放在一个数组中,然后使用 Math.random() 生成索引。您可以使用任何东西作为随机函数的种子(例如当前时间戳)。

// your button
<button onclick='navigate()`>Click Here</button>

// your javascript
const Urls = ['hi.html', 'hi2.html', 'hi3.html'];

function navigate () {
    // Math.Random() * 3 generates a floating point number between [0, 3)
    // Math.floor() converts the decimal number into an integer
    const random = Math.floor(Math.random() * 3);
    
    // Use the url anywhere
    window.location = Urls[random];
}

Example on how to create a random number