【问题标题】:JavaScript link leads to random urlJavaScript 链接导致随机 url
【发布时间】:2021-08-02 09:58:17
【问题描述】:

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

【问题讨论】:

  • 你能补充更多信息吗,因为我不明白你想要什么?
  • 将 URL 放入一个数组中。使用单击事件侦听器,该侦听器选择数组的随机元素并将其放入 this.href

标签: javascript html css url hyperlink


【解决方案1】:

您可以使用将所有三个 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

【讨论】:

    猜你喜欢
    • 2014-01-22
    • 2012-06-06
    • 2014-02-24
    • 2021-06-09
    • 2013-07-15
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多