首页 > 解决方案 > 动态旋转文本和 URL

问题描述

我在页面上有一个 para 元素,定义如下:

在页面加载时,我使用以下脚本将文本和 URL 动态附加到此元素:

$('#nike, #adidas, #cat3').html("<p><strong>Get truly flexible shoes for a long run!</strong><p/><p><a style='color: #b4212f' href='http://example.com/shoes-running-2021' target='_blank'><strong>Get a 20% discount.</strong></a></p>");

到目前为止,这运作良好。但是我现在想旋转文本和网址,以便它随机选择两者之一

$('#nike, #adidas, #cat3').html("<p><strong>Get truly flexible shoes for a long run!</strong><p/><p><a style='color: #b4212f' href='http://example.com/shoes-running-2021' target='_blank'><strong>Get a 20% discount.</strong></a></p>");

或者

$('#nike, #adidas, #cat3').html("<p><strong>Get truly stylish shoes for party wear!</strong><p/><p><a style='color: #b4212f' href='http://example.com/partyshoes' target='_blank'><strong>Get a 10% discount.</strong></a></p>"); 

我该怎么做呢?

标签: jquery

解决方案


您可以使用如下所示的随机数生成器。这是在页面加载时从列表中显示随机消息的一种方式,但在用户刷新页面之前保持静态。

我创建了一个稍微高级一点的过程,它每两秒循环一次消息(你可能想要增加这个计时器)。如果您想在用户不必刷新页面的情况下更改促销信息,这将很有用。


// Get a random number between 0 and 1
r = Math.random();

// If above 0.5 print one message or the other if under 0.5
if (r > 0.5) {

  $('#nike, #adidas, #cat3').html("<p><strong>Get truly flexible shoes for a long run!</strong><p/><p><a style='color: #b4212f' href='http://example.com/shoes-running-2021' target='_blank'><strong>Get a 20% discount.</strong></a></p>");

} else {

  $('#nike, #adidas, #cat3').html("<p><strong>Get truly stylish shoes for party wear!</strong><p/><p><a style='color: #b4212f' href='http://example.com/partyshoes' target='_blank'><strong>Get a 10% discount.</strong></a></p>");

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="nike"></div>
<div id="adidas"></div>
<div id="cat3"></div>

// Create array from promo messages
var promos = [];

// Add promo messages to array
promos.push("<p><strong>Get truly flexible shoes for a long run!</strong><p/><p><a style='color: #b4212f' href='http://example.com/shoes-running-2021' target='_blank'><strong>Get a 20% discount.</strong></a></p");
promos.push("<p><strong>Get truly stylish shoes for party wear!</strong><p/><p><a style='color: #b4212f' href='http://example.com/partyshoes' target='_blank'><strong>Get a 10% discount.</strong></a></p>");

// Set index for promos
promoIndex = 0;

// Update promos at the start
updatePromos();

// This function updates the divs
function updatePromos() {

// Add one to promoIndex to cycle through
  promoIndex = promoIndex + 1;
  
  // Check if promoIndex is above the length of the array of messages
  if (promoIndex >= promos.length) {
    promoIndex = 0
  }

  // Update message
  $('#nike, #adidas, #cat3').html(promos[promoIndex]);

  // Repeat this every 2 seconds
  setTimeout(function() {
    updatePromos();
  }, 2000);

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="nike"></div>
<div id="adidas"></div>
<div id="cat3"></div>


推荐阅读