简体   繁体   中英

I Need Help Randomizing an <a> Tag

I'm in the process of coding a random joke generator, and I was wondering how I could randomize the destination of an tag. I have good JavaScript skills, but as a 12 year old, I'm new to HTML and CSS. I don't know if it matters, but I code on Replit.

My idea is that I have three buttons, each determining the type of joke to generate, and then each has an tag that leads to a separate file with a joke. Currently, I have this

But of course, it only leads to one file, which means one joke, which means sad. I'm thinking that Javascript would be able to fix this, and I could maybe use a tag to import it or something. If you can help, then thank you!

The key is to break it down:

  1. Define your list of possible destinations
  2. Select one at random
  3. Grab the DOM element to change
  4. Set the DOM element's href link to your random page

Here's a working example:

 const destinations = [ 'my-destination-1.html', 'my-destination-2.html', 'my-destination-3.html', 'my-destination-4.html', 'my-destination-5.html' ]; const randomIndex = Math.floor(Math.random()*destinations.length); const randomDestination = destinations[randomIndex]; const randomJokeLink = document.getElementById('random-joke-link'); randomJokeLink.setAttribute("href", randomDestination);
 <a id="random-joke-link" href="#">Random Joke</a>

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