首页 > 解决方案 > ajax/jquery - 将脚本包含在动态网页 (SPA) 中

问题描述

我在本教程中使用 AJAX 和 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");
      });
    

    这是所有相关的页面:

索引.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'不行吗?先感谢您 ...

标签: javascriptjqueryhtmlcssajax

解决方案


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

事件委托

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

将 hello.js 代码更改为此。

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

推荐阅读