简体   繁体   English

如何使用 Javascript 随机播放内部 div 内容?

[英]How to shuffle inner div contents using Javascript?

I want to shuffle the inner contents of a div using javascript. I can shuffle the div positions but cannot shuffle the inner contents.我想使用 javascript 打乱一个 div 的内部内容。我可以打乱 div 的位置,但不能打乱内部内容。 I want to shuffle in such a way that will return like Position 1: Third, Position 2: First, Position 3: Second and so on.我想以这样的方式洗牌,这样会像 Position 1: Third, Position 2: First, Position 3: Second 等等。 I can shuffle the div positions like below but cannot update the contents.我可以像下面那样打乱 div 位置,但不能更新内容。 Can anyone help?谁能帮忙?

 shuffle(); function shuffle() { var container = document.getElementById("mainshuffle"); var elementsArray = Array.prototype.slice.call(container.getElementsByClassName("diffpos")); elementsArray.forEach(function (element) { container.removeChild(element); }); shuffleArray(elementsArray); elementsArray.forEach(function (element) { container.appendChild(element); }); } function shuffleArray(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; }
 <div id="mainshuffle"> <div class="diffpos"> <p>Position 1: First</p> <img src="position1.jpg"> </div> <div class="diffpos"> <p>Position 2: Second</p> <img src="position2.jpg"> </div> <div class="diffpos"> <p>Position 3: Third</p> <img src="position3.jpg"> </div> </div>

If you just want to change the content of p tag refactor your html like this如果您只想更改p tag的内容,请像这样重构您的 html

<div id="mainshuffle">
  <p id="p_shuffle">Position 1: First</p>
  <img class="img_shuffle" src="...">
</div>

Store the content in a array for example:将内容存储在一个数组中,例如:

const contentArr = ['position 1: first', 'position 2: second', 'position 3: third']

then change the content of p tag by using contentArr index like this然后像这样使用 contentArr 索引更改 p 标签的内容

function shuffleContent(i) {
  // i is the index of content you want to use depending on which content you want
  const newContent = contentArr[i];
  const shuffleP = document.getElementById('p_shuffle');
  shuffleP.textContent = newContent;
}

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

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