简体   繁体   中英

Javascript arrays and updating <ul><li></li></ul> elements with a loop?

I'm struggling with this one a little. I'm a junior python developer by trade and I have been asked to build a website. Naturally I said yes and chose Django. Regardless, I'm having a little issue building a calendar widget. I'm using AJAX to pass the request back to the view, and update certain elements based on whether the user is requesting the previous/next month of days.

  function getPreviousMonth( event ) {
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "{% url 'events' %}",
        data: { 'month': previousMonth, 'year': previousYear }
    })
    .done(function(response) {
        console.log(response);
        nextMonth = response.next_month;
        nextYear  = response.next_year;
        previousMonth = response.previous_month;
        previousYear  = response.previous_year;

        currentMonth = response.current_month;
        currentYear  = response.current_year;

        $('#currentMonth').text(currentMonth);
        $('#currentYear').text(currentYear);
    });
  };

This all seems to be working well. In the response object I have an array of lists (I think, certainly correct me if I am wrong). On the template side I am using Django to setup the calendar from an array of days arrays:

  {% for week in weeks %}
  <ul class="days">
    {% for day in week %}
      {% if day == 0 %}
        <li></li>
      {% else %}
        <li>{{ day }}</li>
      {% endif %}
    {% endfor %}
  </ul>
  {% endfor %}

All looks nice (and importantly, functions spot on):

在此处输入图片说明

What I now want to do, is perform the same logic for the unoredered list (class="days") on the template after response is met. I have the days as the following (the "weeks" array, 0 if the day is contained in the month, overwise it has the day of the month as an integer, hopefully this makes sense):

在此处输入图片说明

Above is after clicking on the next month, so this corresponds to the days in February. So for each [] list in the array of lists - I want to go in, and update all li's within a ul - hopefully that makes sense. A loop within a loop essentially.

As I understand it, you want to recreate what you've made with the django template in javascript.

As you're using jQuery this should work:

// Make this selector more specific if needed
$("ul.days").each(function (i) {
    $(this).find('li').each(function (j) {
        if (weeks[i][j]) {
            $(this).html(weeks[i][j]);
        } else {
            $(this).html('');
        }
    });
});

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