简体   繁体   English

如何将 2 个功能放在一起并使其在 javascript 和 html5 中按我的意愿工作

[英]how do I put 2 functions together and make it work as I want in javascript and html5

I am doing a game in which I have to put 100 buttons in a web and touch the start game which will be in the random numbers.我正在做一个游戏,我必须在 web 中放置 100 个按钮,然后触摸随机数的开始游戏。

If I touch it, I win but, I have already done it,如果我碰它,我赢了,但是,我已经做到了,

They are ordered 1,2,3.... 98,99,100 but now I have to shuffle it.他们被订购了 1,2,3.... 98,99,100 但现在我必须洗牌。

I have the shuffle function made but I am trying to fuse it but it doesn't work.我制作了随机播放 function 但我试图融合它但它不起作用。

It works in the console but I want to render it on the page.它在控制台中工作,但我想在页面上呈现它。 See:看:

var arr = []

const doNotDuplicate = (arr) => {
  for (let i = 1; i <= 100; i++) {
    var current = i
    if(arr.indexOf(current) < 0) {
      arr.push(current)

          var btn = document.createElement("button");
          var t = document.createTextNode(i);
          btn.appendChild(t);
          document.querySelector('#container').appendChild(btn) 
    }
  }  
  return arr
}
function shuffle(arr) {
    var i, j, temp;
    for (i = arr.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));    
        swap(arr, i, j);
    }
    return arr;    
}

the swap is what it permits to change its position and shuffle the numbers交换是它允许更改其 position 和洗牌的数字

function setup() {
    if(doNotDuplicate(arr)) {
        setInterval(() => {
            console.log(shuffle(arr))
            shuffle(arr)
        }, 1000

and this is the function I said before.这就是我之前说的function。

It works in the console but It does not work in the page.它在控制台中有效,但在页面中无效。

You can either empty the HTML container and append the array elements again, or you can identify the children indicies and swap them with each other, or (as I'm doing below) collect all children into an array, shuffle that array, then call appendChild with those shuffled children:您可以再次清空 HTML 容器和 append 数组元素,或者您可以识别子索引并将它们相互交换,或者(如下所示)将所有子索引收集到一个数组中,打乱该数组,然后调用appendChild与那些洗牌的孩子:

 const arr = Array.from( { length: 100 }, (_, i) => i + 1 ); const container = document.querySelector('#container'); // Append all buttons for (const num of arr) { container.appendChild(document.createElement('button')).textContent = num; } const children = [...container.children]; start.addEventListener('click', () => { setInterval(() => { // Shuffle children for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [children[i], children[j]] = [children[j], children[i]]; } for (const child of children) { container.appendChild(child); } }, 1000); }, { once: true });
 <div> <button id='start'>START</button> </div> <div id='container'> Press START to begin </div>

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

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