简体   繁体   English

如何使用 JavaScript 抓取随机 div?

[英]How can I use JavaScript to grab a random div?

I'm using JavaScript to create a grid.我正在使用 JavaScript 创建一个网格。 What I'm trying to do is have a random box that is created change colors when I click on the "Play" button but I cannot seem to get it figured out.我想要做的是创建一个随机框,当我点击“播放”按钮时,它会改变颜色,但我似乎无法弄清楚。

I've tried using various amounts of Math.random(), this might be where my problem is.我试过使用各种数量的 Math.random(),这可能是我的问题所在。

 const container = document.getElementById('container'); const gameButton = document.createElement('button'); // This is the button I'm trying to use for this. gameButton.addEventListener('click', function (event) { let getRandom = document.getElementsByTagName('div'); }); let userInput = prompt('Enter a number between 10-20: '); if (isNaN(userInput)) { alert('Numbers only.'); location.reload(); } else if (userInput < 10) { alert('That\\'s less than 10'); location.reload(); } else if (userInput > 20) { alert('That\\'s greater than 20'); location.reload(); } else { gameButton.textContent = 'Play'; gameButton.style.height = '25px'; gameButton.style.width = '50px'; gameButton.style.borderRadius = '7px'; gameButton.style.marginBottom = '15px'; container.appendChild(gameButton); } for (let index = 1; index <= userInput; index++) { let gameBoard = document.createElement('div'); gameBoard.setAttribute('class', 'game-board'); container.appendChild(gameBoard); for (let j = 0; j < userInput; j++) { const square = document.createElement('div'); square.setAttribute('class', 'square'); gameBoard.appendChild(square); } }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="./style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <title>Document</title> </head> <body> <div id="container"> </div> <!---<script src="./app.js"></script>---> </body> </html>

Expected result is one of the 'divs' changes color when the button is clicked on.预期结果是单击按钮时“div”更改颜色之一。

Between your question and your code, it's a little confusing.在您的问题和您的代码之间,这有点令人困惑。 But just going off what you said, here's a way to choose a random element from a list of elements, provided you give it a class name (feel free to tweak this):但只要按照你说的去做,这里有一种从元素列表中选择一个随机元素的方法,前提是你给它一个类名(随意调整):

// Function to get a random number, taking in min and max values.
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)

// Function that takes in a class name to select all those elements
// on the page, and returns a random one from the list.
const getRandomElement = className => {
  const elements = document.querySelectorAll(`.${className}`)
  const num = randomNum(0, elements.length - 1)
  return elements[num]
}

You could change the code in your event listener like this:您可以像这样更改事件侦听器中的代码:

gameButton.addEventListener('click', function (event) {
    let divs = document.getElementsByClassName('game-board');
    let random_div = divs[Math.floor(Math.random()*divs.length)];
    random_div.style.backgroundColor = 'red';
});

Or if you want only one square to change color, use document.getElementsByClassName('square') instead.或者,如果您只想更改一个方块的颜色,请改用 document.getElementsByClassName('square')。

Relevante part o the code.代码的相关部分。 You can make it better checking the elements, the styles, etc. But essentially it is:你可以让它更好地检查元素、样式等。但本质上它是:

gameButton.addEventListener('click', function (event) {
    let getRandom = document.getElementsByTagName('div');
    var a = Math.random()
    let b = a.toString().substr(2, 1)
    getRandom[b].style = 'background-color: ' + (parseInt(b) % 2 == 0 ? 'yellow' : 'red')
});

So you use Math.Random to get some random number after the dot(.) and use it to read some index from the collection you get for the getRandom.因此,您使用 Math.Random 在 dot(.) 之后获取一些随机数,并使用它从 getRandom 获得的集合中读取一些索引。 Then you just set element style or whatever you want.然后你只需设置元素样式或任何你想要的。

The fiddle: https://jsfiddle.net/cm5kyrdj/小提琴: https : //jsfiddle.net/cm5kyrdj/

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

相关问题 如何从 PHP 生成的 div 中获取值并使用 Javascript 然后更改进度条 HTML5 元素的宽度? - How can I grab a value from a PHP generated div and use Javascript to then change the width of a progress bar HTML5 element? 如何获取 PHP 中的 div,该 div 在 javascript function 内的循环中 - How can I grab a div in PHP that's in a loop within a javascript function 如何使用Perl从使用JavaScript动态生成的网页中获取文本? - How can I use Perl to grab text from a web page that is dynamically generated with JavaScript? 如何使用Javascript查找具有随机名称的cookie? - How can I use Javascript to find a cookie with a random name? 如何使用JavaScript在Anki中显示随机字段? - How can I use JavaScript to display a random field in Anki? 如何获取(和使用)在javascript / jQuery中被单击的元素? - How do I grab (and use) the element being clicked in javascript/jQuery? 如何使用 JavaScript 在 div 中抓取文本? - How to grab a text inside a div using JavaScript? 如何获取 HTML 滑块值作为 JavaScript 的整数? - How can I grab an HTML slider value as an integer for JavaScript? 如何从Chrome的JavaScript控制台中获取错误 - How can I grab the error from javascript console in chromium 如何使用 javascript 变量作为 html 的 div id? - How can I use javascript variable as html's div id?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM