Javascript jquery/ajax-带有append函数的事件传播
我正在使用AJAX和JAVASCRIPT(JQUERY)开发单页应用程序,因此我执行以下步骤:Javascript jquery/ajax-带有append函数的事件传播,javascript,jquery,html,Javascript,Jquery,Html,我正在使用AJAX和JAVASCRIPT(JQUERY)开发单页应用程序,因此我执行以下步骤: 首先,我用()获得标签中的链接 之后,我得到了index.html页面中需要包含的页面(另请参阅我之前的文章) 像这样的链接将把页面的代码注入索引页面 index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="vi
<!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>
文件
使用AJAX和JQUERY测试单页应用程序
<select id="typeUser">
<option value="empty">choose type of user</option>
</select>
<button id="btn">say hello world</button>
选择用户类型
向世界问好
var-typeUser=[“用户”、“管理员”];
$(文档).on('click','btn',函数(e)
{
警报(“你好世界”);
});
typeUser.forEach(e=>{
$('select#userType')。追加(''+e+'');
});
提前谢谢。在代码加载到DOM后,您是否尝试将其放入成功回调中
success : function(response) {
console.log("the page was loaded",response);
$('#content').html(response);
let options = '';
$.each(["user" , "administrator"], function(index, type) {
options += `<option>${type}</option>`;
});
$('select#userType').html(options);
}
成功:功能(响应){
log(“页面已加载”,响应);
$('#content').html(回复);
让选项=“”;
$。每个([“用户”、“管理员”],函数(索引,类型){
选项+=`${type}`;
});
$('select#userType').html(选项);
}
不过,SPA的目的不是要将所有代码放在一个地方,这样就不必处理此类问题吗?小旁注<代码>$(this.attr('href')可以是
this.href
href
是dom元素的一个属性。您可以在hello.html中使用onload事件,该事件将触发foreach loopthank You@GilEpshtain方法,但我从未使用过onload,请您举个例子。非常感谢您的回复,在hello.html中包含hello.js有任何缺点。这对谷歌来说是个好问题。这两种风格都有其优缺点,对此也有很多争论。在我看来,根据我的经验,把所有东西都放在一个地方比较容易。它缓解了碎片、服务器响应问题/缺少资源、异步响应的计时(可能是您的问题)。它不必跟踪问题的源文件,从而简化了调试。对于用户体验,改变DOM比联系服务器然后改变DOM要快。虽然这一切都取决于你的项目的情况。
success : function(response) {
console.log("the page was loaded",response);
$('#content').html(response);
let options = '';
$.each(["user" , "administrator"], function(index, type) {
options += `<option>${type}</option>`;
});
$('select#userType').html(options);
}