Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Выбор рандомного элемента из массива для элемента (https://javascript.ru/forum/misc/72117-vybor-randomnogo-ehlementa-iz-massiva-dlya-ehlementa.html)

Бипач 10.01.2018 05:21

Выбор рандомного элемента из массива для элемента
 
Есть 3 дива.

Есть массив с тремя цветами. Допустим, красный, синий и зеленый.

Моя проблема в том, что я не могу понять как при клике на какую-то кнопку каждый из этих трёх элементов приобрел рандомное значение из этого массива. Т.е. изменил бэкграунд.

Пыталась вот так:

var colors = [
        '#ff0000',
        '#00ff00',
        '#0000ff'
    ];

    var random_color = colors[ Math.floor(Math.random() * colors.length) ];

    document.getElementsByClassName('sq')[0].style.backgroundColor =random_color;


Но ничего. Но если использовать вместо class - id, то работает.

Помогите, пожалуйтса

ksa 10.01.2018 08:30

Цитата:

Сообщение от Бипач
Помогите, пожалуйтса

Ты, для начала, пример тестовый полный сделай...

Цвета рандомные могут повторяться?

j0hnik 10.01.2018 15:43

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		.sq{
		width: 100px;
		height: 100px;
		border: 1px solid grey;
		}
	</style>
</head>
<body>
	<div class="sq">Элемент 1</div>
</body>
<script>
	var colors = [
        '#ff0000',
        '#00ff00',
        '#0000ff'
    ];

    document.getElementsByClassName('sq')[0].onclick=e=>e.target.style.backgroundColor = colors[ Math.floor(Math.random() * colors.length)];
    
</script>
</html>

ksa 10.01.2018 16:45

j0hnik, дык
Цитата:

Сообщение от Бипач
Есть 3 дива.


Nexus 10.01.2018 17:02

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		.sq{
			width: 100px;
			height: 100px;
			border: 1px solid grey;
			display:inline-block;
			margin:0 10px;
		}
	</style>
</head>
<body>
	<!-- © j0hnik //-->
	<div class="sq">Элемент 1</div>
	<div class="sq">Элемент 2</div>
	<div class="sq">Элемент 3</div>
	<div>
		<input type="button" value="Какая-то кнопка" id="some_button"/>
	</div>
</body>
<script type="text/javascript">
	var colors = [
        '#f00',
        '#0f0',
        '#00f'
    ];
	
    document.getElementById('some_button').onclick=function(){
		[].forEach.call(document.getElementsByClassName('sq'),function(node){
			node.style.backgroundColor = colors[ Math.floor(Math.random() * colors.length)];
		});
	};
</script>
</html>

Dilettante_Pro 10.01.2018 17:06

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
                body {
                 display: -webkit-flex; 
                 display: flex; 
}
		.sq{
 		width: 100px;
		height: 100px;
		border: 1px solid grey;
		}
	</style>
</head>
<body>
	<div class="sq">Элемент 1</div>
        <div class="sq">Элемент 2</div>
        <div class="sq">Элемент 3</div>
</body>
<script>
	var colors = [
        '#ff0000',
        '#00ff00',
        '#0000ff'
    ];

    document.getElementsByTagName('body')[0].onclick=e=>e.target.style.backgroundColor = colors[ Math.floor(Math.random() * colors.length)];
    
</script>
</html>

Nexus 10.01.2018 17:12

Dilettante_Pro, в вашем примере кнопки недостает :)
Цитата:

Сообщение от Бипач
при клике на какую-то кнопку


Dilettante_Pro 10.01.2018 17:29

Nexus,
независимый вариант - для разнообразия

Бипач 10.01.2018 23:14

Спасибо, уже нашла решение)

<p id="mini"></p>

<div class="flex">

    <div class="shape square"></div>

    <div class="shape circle"></div>

    <div class="shape oval"></div>

</div>

<div id="foo"> Click</div>


$("#foo").click(function () {
        var colors = [
            'green',
            'red',
            'blue'
        ];

        var divs = [
            'square',
            'circle',
            'oval'
        ];

        function compareRandom() {
            return Math.random() - 0.5;
        }

        colors.sort(compareRandom);

        divs.sort(compareRandom);

        document.getElementsByClassName(divs[0])[0].style.backgroundColor = colors[0];
        document.getElementsByClassName(divs[1])[0].style.backgroundColor = colors[1];
        document.getElementsByClassName(divs[2])[0].style.backgroundColor = colors[2];

        var r_class = divs[Math.floor(Math.random() * divs.length)];

        var r_color = colors[Math.floor(Math.random() * colors.length)];

        document.getElementById("mini").innerHTML = "Select " + document.getElementsByClassName(r_class)[0].style.backgroundColor + " " + r_class;

        document.getElementById("mini").style.color = r_color;

        $(".shape").click(function () {
            if (this.style.backgroundColor == document.getElementsByClassName(r_class)[0].style.backgroundColor && ) {
                alert("yep");
            } else {
                alert("no");
            }
        })
    });


Часовой пояс GMT +3, время: 05:48.