使用load从外部html加载jquery,然后分离当前div并再次加载它

时间:2014-10-23 17:48:18

标签: javascript jquery performance load

好的..情景是

的index.html

<body>
<button class="a"> loading file home2.html #home2</button>
<button class="b"> loading file index.html #home</button>
<section id ="a">
  <div id="home">
    blah blah blah
  </div>
</section>
</body>
</html>

和第二个文件

home2.html

<div id="home2">
    bleh bleh bleh
</div>

当我点击按钮1时,我想将home2.html中的所有内容#home2加载到index.html中。 我使用了.load()方法。然后从home2.html加载#home2后我想分离#home(不只是fadeOut()或hide()。但是当我再次点击button2加载#home时,#home内的所有js都无法正常工作。有人帮我吗?

1 个答案:

答案 0 :(得分:0)

这部分是猜测,因为你没有提供足够的信息......但我相信这是一个非常好的猜测。

问题可能是你正在设置绑定元素...然后销毁和重新创建元素并期望绑定仍然存在。它不会以这种方式工作......您必须在创建内容后创建绑定或使用委托。

以下是我认为代表你所拥有的一个例子:

PLNKR - 如果你点击“blah blah blah”,它会在第一次发出警告......但不会在交换内容后发出警告。

  var originalContent = $("#a").html();
  $(".a").click(function() {
    $("#a").load("home2.html");
  });
  $(".b").click(function() {
    $("#a").html(originalContent);
  });
  $("#home").click(function() {
    alert("#home clicked");
  });
  $("#home2").click(function() {
    alert("#home2 clicked");
  });

要使用委派修复它,您可以从#a元素委派代码:

PLNKR - 请注意,无论您更改内容多少次,它都可以正常使用..

  var originalContent = $("#a").html();
  $(".a").click(function() {
    $("#a").load("home2.html");
  });
  $(".b").click(function() {
    $("#a").html(originalContent);
  });
  $("#a").on("click", "#home", function() { //delegating from #a
    alert("#home clicked");
  });
  $("#a").on("click", "#home2", function() {
    alert("#home2 clicked");
  });