简体   繁体   English

我需要帮助随机化<a>标签</a>

[英]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.我有很好的 JavaScript 技能,但作为一个 12 岁的孩子,我是 HTML 和 CSS 的新手。 I don't know if it matters, but I code on Replit.我不知道这是否重要,但我在 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.我在想 Javascript 能够解决这个问题,我也许可以使用标签来导入它或其他东西。 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 Select 随机一个
  3. Grab the DOM element to change抓取要更改的 DOM 元素
  4. Set the DOM element's href link to your random page将 DOM 元素的 href 链接设置为随机页面

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>

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

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