简体   繁体   中英

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.

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:

<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.

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. Same problem with finding '#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:

$(document).ready(function() {
    var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
    update(events);
});

Use the following JS code:

$(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);
     });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM