【问题标题】:Load jquery from external html using load then detach current div and load it again使用 load 从外部 html 加载 jquery,然后分离当前 div 并再次加载
【发布时间】:2014-10-23 17:48:17
【问题描述】:

好吧..场景是

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都不起作用。有人帮我吗?

【问题讨论】:

  • #home 里面有什么 js?你期望人们在没有看到你的 js 的情况下修复你的 js

标签: javascript jquery performance load


【解决方案1】:

这部分是您的猜测,因为您没有提供足够的信息……但我相信这是一个很好的猜测。

问题可能是您正在设置对元素的绑定...然后销毁并重新创建元素并期望绑定仍然存在。它不能这样工作...您要么必须在制作内容后创建绑定,要么使用委托。

以下是我认为代表您拥有的东西的示例:

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");
  });

【讨论】:

    猜你喜欢
    • 2011-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多