【发布时间】:2018-05-14 14:43:39
【问题描述】:
我正在使用 AJAX 和带有this tutorial 的 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"); });这是所有相关的页面:
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