【问题标题】:Loading content into a container div from a button within using jquery使用jquery从按钮将内容加载到容器div中
【发布时间】:2016-10-25 07:09:20
【问题描述】:

这只是对我在这里尝试完成的事情的测试,这可能非常简单,但却让我绞尽脑汁。我已经查看了一些已在此处提供的最接近的匹配项,但我无法使它们中的任何一个起作用。

我正在尝试使用按钮将内容加载到 div 中,如下所示:

<div class="load-container">
  <button class="load-first">Load First</button>
</div>

<script type="text/javascript">
 $(".load-first").click(function() { $(".load-container").load("/test-1.html"); });
 $(".load-second").click(function() { $(".load-container").load("/test-2.html"); });
 $(".load-third").click(function() { $(".load-container").load("/test-3.html"); });
</script>

这实际上在第一次尝试时有效,但是当“/test-1.html”加载时,下一个按钮不起作用。这是 /test-1.html 文件中的内容:

This is the first one.<br>
<button class="load-second">Load Second</button>

单击第二个按钮应该加载下一个内容,但它什么也不做。问题是按钮位于目标容器 div 内吗?我需要一个带有按钮的容器 div,可以通过这种方式加载新内容。

【问题讨论】:

    标签: jquery-load


    【解决方案1】:

    因为在页面加载时,“load-second”按钮还没有出现,因此 click() 事件没有注册到尚未通过 load() 内容出现的按钮,您需要要在 DOM 中创建按钮后附加事件,请尝试以下操作:

    <div class="load-container">
      <button class="load-first">Load First</button>
    </div>
    
    <script type="text/javascript">
         $(".load-first").click(function() { 
            $(".load-container").load("/test-1.html", function(){  
            // now load-second button is available, register the click handler
            $(".load-second").click(function() { 
                $(".load-container").load("/test-2.html", function(){
                // now load-third button is available, register the click handler
                $(".load-third").click(function() { $(".load-container").load("/test-3.html"); });
                });
            });
           });
    });
    
    </script>
    

    【讨论】:

    • 请原谅我的经验不足,您的回答似乎有道理,但您提供的内容在加载第一个 /test-1.html 后似乎不起作用,这是它之前所做的。 /test-1.html 中的按钮一旦加载到 .load-container 中就不起作用。
    • 是的,我已经更新了代码以使用 load() 函数的回调,因为您可以在 load() 函数的第二个参数中传递回调函数,以便在加载内容后执行,这将确保在内容加载后执行点击事件注册。
    • 太好了,您可以通过将此解决方案标记为答案来结束问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多