【问题标题】:ajax/jquery - including script into a dynamic web page (SPA)ajax/jquery - 将脚本包含在动态网页 (SPA) 中
【发布时间】:2018-05-14 14:43:39
【问题描述】:

我正在使用 AJAX 和带有this tutorial 的 JAVASCRIPT(JQUERY) 设置单页应用程序:

  1. 首先我得到<a>标签中的链接:

     $('a').on('click',function(event)
     {
         event.preventDefault();
         var pageRef = $(this).attr('href');
         callPage(pageRef);
      });
    
  2. 之后,我通过此代码获得了包含在 index.html 页面中的页面:

    function callPage(url)
    {
    $.ajax({
        url : url,
        type: "GET",
        dataType : "text",
        success : function(response)
        {
            console.log("the page was loaded",response);
            $('#content').html(response);
        },
        error : function(error)
        {
            console.log("the page wasn't loaded",error);
        },
        complete : function(xhr , status)
        {
            console.log("the requeste is complete");
        } 
    });
     }
    
  3. 最后我在 hello.js 中有这个测试脚本:

     $('#btn').on('click',function()
      {
           alert("hello world");
      });
    

    这是所有相关的页面:

index.html:

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <meta http-equiv="X-UA-Compatible" content="ie=edge">
          <title>Document</title>
      </head>
      <body>

      <div id="main">
              <h1>TEST SINGLE PAGE APPLICATION WITH AJAX AND JQUERY</h1>
              <ul>
                   <li><a href="./about.html">about</a></li>
                   <li><a href="./contact.html">contact</a></li>
                   <li><a href="./hello.html">hello</a></li>
              </ul>
              <div id="content"></div>
      </div>


      <script src="./js/jquery.min.js"></script>
      <script src="./js/script.js"></script>
      <script src="./js/hello.js"></script>
      </body>
      </html>

你好.html:

      <button id="btn">say hello world</button>

现在一切正常,但是当我单击#btn 时不会出现警报消息,但是当我在 hello.html 页面中包含 hello.js 文件时,它的工作原理,有人可以告诉我第一种情况的原因不工作?因为当 jquery 包含页面(hello.html)并在 index.html 中包含脚本(hello.js)时,hello.html 和 hello.js 会在同一个地方,所以为什么按钮 #btn don'不行吗? 提前谢谢你...

【问题讨论】:

  • 因为当点击处理程序代码试图找到它时,该按钮还不存在。

标签: javascript jquery html css ajax


【解决方案1】:

您需要为您的 ajax 内容使用事件委托。

Event Delegation

事件委托是指使用事件传播的过程 (冒泡)在 DOM 中处理比 事件起源的元素。它允许我们附加一个 现在或将来存在的元素的事件监听器。

将 hello.js 代码更改为此。

$(document).on("click", '#btn', function(event) { 
    alert("hello world");
});

【讨论】:

  • 非常感谢您的快速响应以及代码。
  • 如果这个答案对你有帮助。请接受它,这样它也可以帮助其他有类似问题的人
  • 欢迎@ekka :)
  • 你能分享以上文档的链接吗?
  • 完成了 ekka。 :)
【解决方案2】:

您将单击事件附加到 DOM 尚不存在的按钮,因为您的 hello.html 尚未呈现。这就是它不起作用的原因。

【讨论】:

    猜你喜欢
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    • 2010-09-19
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多