1

我正在尝试使用 jquery 查找和替换 html 数据。jquery 脚本正在工作,事实上它正在从一个 div 容器中获取 html 数据并将其替换为新数据。问题在于重新加载它是复制容器类,而不是添加计算以下 div 所需的 masonry-brick 类。

这是JQuery:

$("div.more a").on("click", function (event) {
   event.preventDefault();
   // get the contents
    $.get(this.href, function (response) {
        // jquerify the response HTML string and find our replaceable area
        var result = $(response).find('.l-home-grid');
        // do the replace
        $('.l-home-grid').html(result);
    });
  // Revert all to original state
  $("a.active")
    .removeClass("active")
    .addClass("static");
  // Set classes to clicked anchor
  $(this)
    .removeClass("static")
    .addClass("active");

  window.location.hash = $(this).text();
});

这导致了html:

<div class="mobile-padding l-home-grid masonry" style="position: relative; height: 2660px; ">
  <div class="mobile-padding l-home-grid">
    <div class="gridCells"><a href="#">
      <h4>Things</h4>
      <img width="256" height="182" src="foo.jpg"> </a></div>
    <div class="gridCells"><a href="#">
      <h4>More Things</h4>
      <img width="256" height="182" src="foo.jpg"> </a></div>
    <div class="gridCells"><a href="#">
      <h4>Objects</h4>
      <img width="256" height="182" src="foo.jpg" > </a></div>
  </div>
</div>

为什么是

<div class="mobile-padding l-home-grid masonry" style="position: relative; height: 2660px; ">
      <div class="mobile-padding l-home-grid"> 

加载两次?

目标是这样的:

<div class="mobile-padding l-home-grid masonry" style="position: relative; height: 2660px; ">
    <div class="gridCells masonry-brick"><a href="#">
      <h4>Things</h4>
      <img width="256" height="182" src="foo.jpg"> </a></div>
   ...
4

1 回答 1

1

发生这种情况是因为您将.l-home-grid响应中的整个元素添加到现有.l-home-grid元素中。更改此行:

var result = $(response).find('.l-home-grid');

对此:

var result = $(response).find('.l-home-grid').html();

为了将响应内容添加到您的容器中。您可能需要致电

$('.l-home-grid').masonry('reload');

在您拉入新内容以确保其获得砌体化之后。

于 2012-06-26T16:46:25.037 回答