javascript - 以随机顺序动态地将div添加到另一个div中

标签 javascript jquery html

我正在尝试打乱关键字列表并将它们放入文本幻灯片中的各个 div 中。

这是我的脚本:

var keys = ["dancing.", "computers.", "food.", "movies.", "singing.", "hiking.", "math.", "music.", "reading.", "cars.", "laughing.", "animals.", "cupcakes.", "shopping.", "soccer.", "Europe.", "photography.", "volunteering.", "outerspace.", "traveling.", "guitar.", "painting.", "children.", "boats.", "science.", "art.", "cheerleading.", "Einstein.", "teaching.", "politics.", "waterskiing.", "volleyball.", "whittling.", "volleyball.", "running.", "comedy.", "theater.", "Africa."];

keys.sort(function() { return Math.floor(Math.random()*3 -1)});

for(i = 0; i < keys.length; i++) {
    ("<div>" + keys[i] + "</div>").appendTo("slideshow");   
}

function randomize(myArray) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
}
<小时/>
<td class="align-top">
   <div class="slideshow"></div>
</td>
<小时/>

有什么想法吗?我还认为我没有很好地融合 javascript 和 jQuery。你能帮我清理一下吗?

最佳答案

试试这个:

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

var $slideshow = $(".slideshow");
for(var i = 0; i < keys.length; i++) {
    $slideshow.append("<div>" + keys[i] + "</div>");   
}

演示:http://jsfiddle.net/XpyYX/1/

您的代码不起作用,因为在这一行:

("<div>" + keys[i] + "</div>").appendTo("slideshow");

您在开始 ( 之前遗漏了 $jQuery,因为您想附加到 ".slideshow “(带有 .)按类选择元素。它的工作方式如下:

$("<div>" + keys[i] + "</div>").appendTo(".slideshow");

...但缓存对幻灯片元素的引用应该更有效。

此外,您的随机排序过于复杂。

关于javascript - 以随机顺序动态地将div添加到另一个div中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12549112/

相关文章:

javascript - 在 Angular 中使用持久性 CSRF-TOKEN cookie 的风险

javascript - 用占位符定义常量

javascript - 弃用的 jQuery 回调 - 澄清?

c# - 在发布之前重新显示所有表单输入

javascript - jquery when 文档的响应和错误

javascript - jQuery ui 可排序 toArray 跳过 1 项

jquery - 设置变量未定义和 null

javascript - 从 jquery.is 函数中使用的选择器中获取匹配的元素

php - 从小写到大写

html - 使用 CSS3 关键帧动画 div 滑动,但 div 插入其他 div