我正在使用AJAX和JAVASCRIPT(JQUERY(处理单页应用程序,所以我执行以下步骤:
-
首先,我获得了标签中的链接(请参阅我之前的帖子(。
-
之后,我得到了需要包含在索引.html页面中的页面(另请参阅我之前的帖子(。
像这样,A 链接将页面的代码注入索引页面。
-
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 :
<select id="typeUser"> <option value="empty">choose type of user</option> </select> <button id="btn">say hello world</button>
-
这是你好.html页面的脚本(你好.js(:
var typeUser = ["user" , "administrator"]; $(document).on('click','#btn',function(e) { alert("hello world"); }); typeUser.forEach(e =>{ $('select#userType').append('<option>'+e+'</option>'); });
问题是当foreach循环开始时div#content为空,并且select#userType尚不存在,我想要的是将数组typeUser加载到select#typeUser标签中,而无需将脚本hello.js包含在hello.html页面中。
提前谢谢你。
您是否尝试过在代码加载到 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);
}
虽然,SPA的重点不是将所有代码放在一个地方,这样您就不必处理此类问题吗?