我是JavaScript的新手,试图绘制一个数值为1-9的数字网格。点击两个按钮进行随机播放和排序。 the grid I am looking for
我可以随机播放数字,但无法将它们分配回div。任何帮助深表感谢。
还需要帮助将十六进制颜色值(显示在img中)传递给每个div。
$(".btn_shuffle").click(function () {
var cardNumbers = [];
$('.card').each(function () {
cardNumbers.push(this.innerHTML);
});
var theLength = cardNumbers.length-1;
var toSwap ;
var temp;
console.log(cardNumbers);
for(i=theLength; i>0; i--){
toSwap = Math.floor(Math.random()*i);
temp = cardNumbers[i];
cardNumbers[i] = cardNumbers[toSwap];
cardNumbers[toSwap]=temp;
}
console.log(cardNumbers);
});
答案 0 :(得分:0)
$(".btn_shuffle").click(function () {
var cardNumbers = [];
$('.card').each(function () {
cardNumbers.push(this.innerHTML);
});
var theLength = cardNumbers.length-1;
var toSwap;
var temp;
// console.log(cardNumbers);
for (var i = theLength; i > 0; i--) {
toSwap = Math.floor(Math.random() * (i + 1));
temp = cardNumbers[i];
cardNumbers[i] = cardNumbers[toSwap];
cardNumbers[toSwap] = temp;
}
// console.log(cardNumbers);
// adding them back, i is already =0 from the above loop, so we just use it again
$('.card').each(function () {
this.innerHTML=cardNumbers[i];
i++;
});
//
});

#shuffle > div {
float: left;
line-height: 30px;
width: 50px;
text-align: center;
background-color: steelblue;
color: #fff;
border-radius: 4px;
margin: 3px;
}
#shuffle {
max-width: 360px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn_shuffle" id="shuffle">Shuffle</button>
<button class="btn_sort">Sort</button>
<div id="shuffle">
<div class="card">1</div>
<div class="card">2</div>
<div class="card">3</div>
<div class="card">4</div>
<div class="card">5</div>
<div class="card">6</div>
<div class="card">7</div>
<div class="card">8</div>
<div class="card">9</div>
</div>
&#13;