[英]How to select a random variable from a list for each iteration of a PHP generated for-each loop?
For each time my php code loops, it creates a new card for a cart item. 每次我的php代码循环时,它都会为购物车项目创建一张新卡。 I would like to have the background color of the card to be selected randomly from a list for each different card. 我想从每个不同卡的列表中随机选择卡的背景颜色。
I added script to pick a random color and jquery selected the card, but it only changed the first item of the loop, and the rest are unaffected by the the jquery. 我添加了脚本以选择随机颜色,然后jquery选择了卡片,但它仅更改了循环的第一项,其余部分不受jquery的影响。
HTML + PHP: HTML + PHP:
<?php foreach($sArray as $sizeString){ ?>
div id="item_card" class = "cart_item_wrapper" >
<?php } ?>
script: 脚本:
var colors = ['#ff0000', '#00ff00', '#0000ff'];
var random_color = colors[Math.floor(Math.random() * colors.length)];
$('#item_card').css('background-color', random_color);
So, this only affects the first item card, I would like for every card's color to be randomly selected from the "colors" variable. 因此,这仅影响第一张卡片,我希望从“颜色”变量中随机选择每张卡片的颜色。 Thank you. 谢谢。
PHP: PHP:
div class="cart_item_wrapper item_card"
JS: JS:
$('.item_card').css('background-color', random_color);
I know, right? 我知道,对吧?
Make item_card id unique by concatenating a random number or an index of the looping array. 通过串联循环数组的随机数或索引,使item_card id唯一。 Then, pass that to the script function as a parameter and use to apply the color. 然后,将该参数作为参数传递给脚本函数,并用于应用颜色。
For example: 例如:
<?php foreach($sArray as $index=> $sizeString){?>
<div id="item_card<?php echo $index?>" class = "cart_item_wrapper"></div>
<?php } ?>
Then, 然后,
function pickColor(index) {
var colors = ['#ff0000', '#00ff00', '#0000ff'];
var random_color = colors[Math.floor(Math.random() * colors.length)];
$('#item_card' + index).css('background-color', random_color);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.