简体   繁体   中英

I'm trying to create a button that links to a random page

I'm new to coding and I'm trying to create a button that links to a random page in my simple website. I'm having issues modifying the "href" and making it go to the page on the click.

Here is the JavaScript I have written:

document.addEventListener("DOMContentLoaded", function(){
let arrayofpages = ["my_cat.html","about_me","art.html","index.html"]
let randompage = arrayofpages[Math.floor(Math.random()*arrayofpages.length)];

document.addEventListener("click",function(){
document.getElementById("lucky_btn").href = "${randompage}";
document.getElementById("lucky_btn").innerHTML = "random page";
});

I would appreciate any help I can get!

The string "${randompage}" is literally just a string that says "${randompage}" . Instead, use backticks:

`${randompage}`  // This creates a string out of the variable randompage

But in your case, since you're not doing anything with the string, the simplest way is to use the variable directly:

document.getElementById("lucky_btn").href = randompage;

In general, template literals are more useful for inserting variables into a longer string, like

let name = 'Sarah';
let quality = 'great';
let message = `Hello ${name}, have a ${quality} day`;

A little bug in your code. you used double quotes "" instead of backticks `` .

This line

document.getElementById("lucky_btn").href = "${randompage}";

should be

document.getElementById("lucky_btn").href = `${randompage}`;

Thank you for all the answers looking at them I have found the bug that was causing the issue, of not redirecting to a random page:

instead of

document.getElementById("lucky_btn").href = "${randompage}";

where I should have used backticks, I changed the code to:

 document.location.href = `${randompage}`;

and this has solved the problem!

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.

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