[英]creating a list in html using jQuery append not working
I've been staring at this code for hours now, any input appreciated. 我已经盯着这个代码好几个小时了,感谢任何输入。
I want to create a list in a HTML file from an array of objects using jquery append, but it justs stays blank. 我想使用jquery append从对象数组中的HTML文件中创建一个列表,但它保持空白。
HTML: HTML:
<html>
<head>
<script src="jquery-1.10.0.js"></script>
<script src="test.js"></script>
<title></title>
</head>
<body>
<div id="list">
</div>
<div id="template">
<div class="info">
<a class="url"></a>
</div>
</div>
</body>
</html>
Script: 脚本:
function update(events) {
var eventList = $('#list');
eventList.empty();
events.forEach(
function(_event) {
var eventsHtml = $('#template .info').clone();
eventsHtml.find('.url').text(_event.title)
.attr('href', _event.url);
eventList.append(eventsHtml);
});
}
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
update(events);
Assuming the JS code you show is contained in test.js, either move this line: 假设您显示的JS代码包含在test.js中,请移动以下行:
<script src="test.js"></script>
...to the end of the body (just before the closing </body>
tag), or wrap your code in a $(document).ready()
handler. ...到正文的末尾(恰好在
</body>
标记之前),或将代码包装在$(document).ready()
处理程序中。
The way you currently have it, this line: 您当前拥有它的方式,此行:
var eventList = $('#list')
...doesn't find the '#list'
element because the script runs before the element is parsed. ...找不到
'#list'
元素,因为脚本在解析该元素之前运行。 Same problem with finding '#template .info'
. 查找
'#template .info'
同样的问题。
You could wrap all of the code in a ready handler, or if you need to be able to call the update()
function from elsewhere just wrap the initial call: 您可以将所有代码包装在一个就绪的处理程序中,或者如果您需要能够从其他地方调用
update()
函数,则只需包装初始调用即可:
$(document).ready(function() {
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
update(events);
});
Use the following JS code: 使用以下JS代码:
$(document).ready(function(){
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
var eventList = $('#list');
eventList.empty();
events.forEach(
function(_event) {
var eventsHtml = $('#template .info').clone();
eventsHtml.find('.url').text(_event.title)
.attr('href', _event.url);
eventList.append(eventsHtml);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.