Springboot项目-blog(三)

需求:根据后端返回的JSON数组,动态的加载div,比如后端返回4组数据,就动态生成4个div,并将返回的数据内容显示出来

操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<script>
// 页面加载时就ajax
$(document).ready(function () {
$.ajax({
async: false,
url: "http://localhost:8888/selectArticle",
type: "GET",
data: {pageNum: 1, pageSize: 10},
error: function (error) {
console.log(error);
},
success: function (data) {
// $('.articles').empty();
// $('.content').empty();
var articles = $('.grid');
var content = $('.content');
$.each(data, function (i, obj) {
var center = $('<a class="grid__item" href="#">' +
'<h2 class="title title--preview">' + obj['articleTitle'] + '</h2>' +
'<div class="loader">' + '</div>' +
'<span class="category">' + obj['articleTabloid'] + '</span>' +
'<div class="meta meta--preview">' +
'<span class="meta__date">' + '<i class="fa fa-calendar-o">' + '</i>' + obj['articleDate'] + '</span>' +
'<span class="meta__reading-time">' + '<i class="fa fa-clock-o">' + '</i>' + obj['articleAuthor'] + '</span>' +
'</div>' +
'</a>'
);

var tent = $('<div class="scroll-wrap">' +
'<article class="content__item">' +
'<span class="category category--full">Stories for humans</span>' +
'<h2 class="title title--full">' + obj['articleTitle'] + '</h2>' +
'<div class="meta meta--full">' +
'<span class="meta__author">' + obj['articleAuthor'] + '</span>' +
'<span class="meta__date"><i class="fa fa-calendar-o"></i>' + obj['articleDate'] + '</span>' +
'<span class="meta__reading-time"><i class="fa fa-clock-o"></i> 3 min read</span>' +
'</div>' +
'<p>正文</p>' +
'</article>' +
'</div>'
);
articles.append(center);
content.append(tent);
})
}
})
});
</script>

但是这样会发现js失效了,原因是是Ajax在载入新的dom之前就已经把页面的JS加载完了,再执行事件时,没有绑定到新载入的dom上,所以我的解决方法是将js也动态加载,根据我的了解$(document).ready()的方法是执行在·、window.onload = function (){}前的,所以我使用$(document).ready()首先加载div框架,加载完毕之后,再使用window.onload = function (){}方法加载js,那么就能保证JS最后加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!--动态加载JS-->
<script>
window.onload = function () {
var body = $("body");
<!--此处添加需要动态加载的js-->
var js = $(
'<script src="../static/assets/js/modernizr.custom.js">' +
'\<\/script>' + '<script src="../static/assets/js/classie.js">' +
'\<\/script>' + '<script src="../static/assets/js/count.js">' +
'\<\/script>'
);
body.append(js);
};
</script>
赏个🍗吧
0%