在动态生成的DOMElement

时间:2016-07-21 08:21:42

标签: javascript jquery html css

我正在尝试使用生成的div块创建一个砌体显示。 结构如下:

<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>
	  <div class="post"> <!-- The .post are generated dynamically -->
        <!-- Block content generated dynamically  -->
      </div>
    </div>
  </div>
</div

和jQuery:

jQuery(window).load(function () {



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

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



	// Creates an instance of Masonry on #posts

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

每次加载页面时,都会收到错误:未捕获的TypeError:container.masonry不是函数。 我是jQuery的新手,这就是我使用here

中的砌体模板的原因

我已经将一些帖子看作:Event binding on dynamically created elements? 但我无法弄清楚如何解决我的问题。我想错误发生是因为我试图将事件绑定到尚未创建的元素。

2 个答案:

答案 0 :(得分:0)

适用于我... ID必须在您的标记中唯一2个标记具有相同的ID,可能与.post有问题,因为空...链接到masonry.js不好assets/js/masonry.js < / p>

&#13;
&#13;
jQuery(window).load(function () {



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

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



	// Creates an instance of Masonry on #posts

	container.masonry({
		gutter: gutter,
		itemSelector: '.post',
		columnWidth: '.post'
	});
});
&#13;
<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>
	  <div class="post"> 
        <p> The .post are generated dynamically </p>
        <p> Block content generated dynamically </p>
      </div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我通过删除

解决了这个问题

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
&#13;
&#13;
&#13;

一行,因为我已经从另一个包含的文件导入它 ...我的不好!

感谢您的帮助,祝您度过愉快的一天!