2016-11-23 84 views
-1

我试图用这个小提琴http://jsfiddle.net/C6LPY/2/

$(function() { 
    var parent = $("#shuffle"); 
    var divs = parent.children(); 
    while (divs.length) { 
     parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]); 
    } 
}); 

在我的网站在这里:

https://github.com/craiglockwood/confheroes/blob/master/index.html但我得到一个“找不到变量”错误。

的想法是,在每次重新洗牌的div随机顺序加载页面。小提琴作品,但不知何故,没有跟我的代码。

任何帮助非常appre ciated。

+0

那么问题可能在于不包含在小提琴代码。尝试进一步缩小范围。 –

+1

你已经在页面的'head'中使用了帖子中的代码片段,但是直到'body'的底部才会包含jQuery。你想在页面知道它是什么之前使用jQuery。你可以将你的代码片段移动到jQuery包含之后,或者在你的代码片段之前将jQuery包括到'head'中。 – Santi

+0

您的代码缺少jQuery库。 – spooky

回答

0

顺序很重要

移动的内嵌JavaScript的脚本后,您IIFE引用jQuery的 - 无论是在head元素或朝向body元素的结束(读this post,了解更多有关把他们的利益朝向body元件的末尾)。否则,jQuery代码将不可用于内联脚本。有关包含外部脚本的更多信息,请参阅this guide

<script type='text/javascript'> 
 
    //jQuery should not be loaded yet, so typeof $ should return undefined 
 
    console.log('typeof $ before including jQuery: ',typeof $); 
 
</script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<script src="assets/js/bootstrap.min.js"></script> 
 
<!-- at this point, jQuery should be defined, and $ should be usable as a shortcut for it.--> 
 
<script type='text/javascript'> 
 
    //ensure typeof $ is a function, otherwise it is likely the case that jQuery did not load 
 
    console.log('typeof $ after including jQuery: ',typeof $); 
 
    $(function() { 
 
    var parent = $("#shuffle"); 
 
    var divs = parent.children(); 
 
    while (divs.length) { 
 
     parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]); 
 
    } 
 
    }); 
 
</script> 
 
<div id="shuffle">ShuffleDiv 
 
    <div>child div 1</div> 
 
    <div>child div 2</div> 
 
    <div>child div 3</div> 
 
</div>