我的页面上有4个div
个项目,我正在尝试让这些项目的内部html随机淡出,从数组中取一行然后将其淡入 - 在它的位置,这样做合理?
// My items that I would like to repopulate the faded out info
var testimonialsArray = [
"<div class='change'><h1>Box 5</h1><p>Lorem ipsum</p></div>",
"<div class='change'><h1>Box 6</h1><p>Lorem ipsum</p></div>",
"<div class='change'><h1>Box 7</h1><p>Lorem ipsum</p></div>",
"<div class='change'><h1>Box 8</h1><p>Lorem ipsum</p></div>",
"<div class='change'><h1>Box 9</h1><p>Lorem ipsum</p></div>"
];
// Find a random div and fade it out
var order = Math.floor((Math.random()* $('.change').length )+1);
$('.box').eq(order).find('.change').fadeOut();
.......Fade in new data from an array row
答案 0 :(得分:2)
基于我认为你想做的事情:
var order = Math.floor((Math.random()* $('.change').length ));
$('.box').eq(order).find('.change').fadeOut(function(){
$(this).html(testimonialsArray[Math.floor((Math.random()* testimonialsArray.length))]).fadeIn();
});
JSFiddle: http://jsfiddle.net/crn7dysu/4/
答案 1 :(得分:0)
假设您从Math.random()
获得0而$('.change').length
为10
Math.floor((0 * 10) + 1);
您可以看到此代码永远不会生成0作为输出。
这个将生成所有可能的组合:
Math.floor(Math.random()* $('.change').length);
答案 2 :(得分:0)
您可以使用此脚本:
var testimonialsArray = [
"<div class='change'><h1>Box 5</h1><p>Lorem ipsum</p></div>",
"<div class='change'><h1>Box 6</h1><p>Lorem ipsum</p></div>",
"<div class='change'><h1>Box 7</h1><p>Lorem ipsum</p></div>",
"<div class='change'><h1>Box 8</h1><p>Lorem ipsum</p></div>",
"<div class='change'><h1>Box 9</h1><p>Lorem ipsum</p></div>"
];
var order = Math.floor((Math.random()* $('.box').length )+1);
var newOrder = Math.floor((Math.random()* testimonialsArray.length ));
$('.box:nth-child('+order+')').find(".change").fadeOut( function() {
$(testimonialsArray[newOrder]).appendTo('.box:nth-child('+order+')').hide().fadeIn('slow');
});