2016-07-21 50 views
0

應用的jQuery我試圖創建生成的div塊砌築顯示。 的strutcture如下:動態生成一個DOMElement

<div id="grid" class="panel"> 
 
    <div id="grid"> 
 
    <div id="posts"> 
 
     
 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
 
     <script src="https://cdnjs.cloudflare.com/ajax/libs/masonry/3.3.2/masonry.pkgd.js"></script> 
 
     <script src="assets/js/masonry.js"></script> 
 
     
 
     <div class="post"> <!-- The .post are generated dynamically --> 
 
     <!-- Block content generated dynamically --> 
 
     </div> 
 
\t <div class="post"> <!-- The .post are generated dynamically --> 
 
     <!-- Block content generated dynamically --> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</div

而jQuery的:

jQuery(window).load(function() { 
 

 

 

 
\t // Takes the gutter width from the bottom margin of .post 
 

 
\t var gutter = parseInt(jQuery('.post').css('marginBottom')); 
 
\t var container = jQuery('#posts'); 
 

 

 

 
\t // Creates an instance of Masonry on #posts 
 

 
\t container.masonry({ 
 
\t \t gutter: gutter, 
 
\t \t itemSelector: '.post', 
 
\t \t columnWidth: '.post' 
 
\t }); 
 
    /* 
 
    * some code 
 
    */ 
 
});

每次加載頁面時,我得到的錯誤:Uncaught TypeError:container.masonr y不是函數。 我在jQuery的新手,這就是爲什麼我用磚石模板從here

我已經看了一些帖子爲:Event binding on dynamically created elements? 但我無法弄清楚如何解決我的問題。我想這個錯誤發生是因爲我試圖將事件綁定到尚未創建的元素上。

+1

您似乎在您的頁面中包含石工兩次,我會刪除非CDN版本 –

+0

爲什麼不嘗試在''' –

+0

中加載您的js文件CDN版本允許我使用** jQuery(' .post')container({...}); **因爲我的資產/ js/masonry.js沒有包含容器構造函數的定義。 –

回答

0

作品對我來說... ID必須爲你的獨特標記2個標籤具有相同的ID,用.post因爲空也許問題...鏈接masonry.js不好assets/js/masonry.js

jQuery(window).load(function() { 
 

 

 

 
\t // Takes the gutter width from the bottom margin of .post 
 

 
\t var gutter = parseInt(jQuery('.post').css('marginBottom')); 
 
\t var container = jQuery('#posts'); 
 

 

 

 
\t // Creates an instance of Masonry on #posts 
 

 
\t container.masonry({ 
 
\t \t gutter: gutter, 
 
\t \t itemSelector: '.post', 
 
\t \t columnWidth: '.post' 
 
\t }); 
 
});
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/masonry/3.3.2/masonry.pkgd.js"></script> 
 
<script src="assets/js/masonry.js"></script> 
 
<div class="panel"> 
 
    <div id="grid"> 
 
    <div id="posts"> 
 
      
 
     <div class="post"> 
 
     <p> The .post are generated dynamically</p> 
 
     <p> Block content generated dynamically</p> 
 
     </div> 
 
\t <div class="post"> 
 
     <p> The .post are generated dynamically </p> 
 
     <p> Block content generated dynamically </p> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</div>

+0

謝謝,我在排序導入失敗.. jQuery需要首先加載,它被加載兩次..所以它產生了錯誤 –

0

我通過移除

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
解決的問題

行,因爲我是導入它已經從另一個包含文件 ...我的壞!

感謝您的幫助球員,並有一個愉快的一天!