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?
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. It must be inside a certain area, eg the onclick property:
<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()
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 .
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.