简体   繁体   English

如何在链接后添加随机数

[英]How to add a random number after a link

I have a link and I want to add a random number after this link every time that page is load. 我有一个链接,我想在每次加载该页面时在此链接后添加一个随机数。

How can I do this? 我怎样才能做到这一点?

Is there a way to add random number in href tag without any separate jquery code? 有没有一种方法可以在href标签中添加随机数而无需任何单独的jquery代码?

i wrote the below code but it does not work. 我写了下面的代码,但它不起作用。

<a href="secondpage?rand=+Math.Random()">click</a>

You cant just mix in javascript somewhere on your page. 您不能只在页面的某处混入JavaScript。 It must be inside a certain area, eg the onclick property: 它必须在某个区域内,例如onclick属性:

<a onclick="location.href = `secondpage?rand=${Math.random()}`">click</a>

Because this is usually a bad idea, we could have a script that modifies all links on the page and adds the random number: 因为这通常是一个坏主意,所以我们可以使用一个脚本来修改页面上的所有链接并添加随机数:

<script>
  window.onload = () => {
    document.querySelectorAll("a").forEach(link =>
      link.href += "?rand=" + Math.random()
    );
  };
</script>

The syntax for random number generation is Math.random() 随机数生成的语法是Math.random()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

In order to assign the random number to the href manipulate the DOM . 为了给href分配随机数 ,请操作DOM

Here is an example: 这是一个例子:

<html>
  <body>
  <div id="foo"> </div>
  <script>
    var a = document.createElement('a');
    a.href="secondpage?rand="+Math.random();
    a.innerText = "click";
    var div = document.getElementById('foo');
    div.appendChild(a);
  </script>
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM