2016-11-23 85 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>