javascript - ajax/jquery - 将脚本包含在动态网页 (SPA) 中
问题描述
我在本教程中使用 AJAX 和 JAVASCRIPT(JQUERY) 设置单页应用程序:
首先,我
<a>
使用以下代码获取标签中的链接:$('a').on('click',function(event) { event.preventDefault(); var pageRef = $(this).attr('href'); callPage(pageRef); });
之后,我通过此代码获得了包含在 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"); } }); }
最后我在 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'不行吗?先感谢您 ...
解决方案
您需要为您的 ajax 内容使用事件委托。
事件委托是指使用事件传播(冒泡)来处理 DOM 中比事件起源的元素更高级别的事件的过程。它允许我们为现在或将来存在的元素附加一个事件侦听器。
将 hello.js 代码更改为此。
$(document).on("click", '#btn', function(event) {
alert("hello world");
});
推荐阅读
- c - “标记输出”的含义 - “C 编程 - 现代方法 2”中的练习
- c++ - 如何优化 CLIPS 中不同模板化事实之间的模式匹配
- python - 使用 Python 和 selenium 从 Tweet 中提取 YouTube 链接
- socket.io - Socket.io:在 socket.io 聊天应用程序中的每条新消息后,我是否需要断开客户端?
- node.js - 添加 NavLink 后如何修复“× TypeError: Cannot read property 'pathname' of undefined”?
- php - 如何将 json Web 令牌转换为 json 对象?
- python - 如何让 argparse 为具有两个名称的 python 脚本显示一个帮助页面?
- python - 使用宏插入更多宏
- php - 用axios发布后获取返回的数据(vue+laravel)
- python - 此 R 代码是否有 python 进程