[英]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.
我是一名初级python程序员,因此被要求建立一个网站。 Naturally I said yes and chose Django.
我自然会说“是”,然后选择了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.
我正在使用AJAX将请求传递回视图,并根据用户是否在请求前几天/下个月来更新某些元素。
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:
在模板方面,我使用Django从days数组中设置日历:
{% 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. 我现在想做的是,在响应得到满足之后,对模板上的未加密列表(class =“ days”)执行相同的逻辑。 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):
我有以下天数(“ weeks”数组,如果月份中包含星期几,则为0,否则将月份中的星期几作为整数,希望这是有意义的):
Above is after clicking on the next month, so this corresponds to the days in February. 上面是单击下个月后的日期,因此它对应于2月中的日期。 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.
因此,对于列表数组中的每个[]列表-我想进入并更新ul中的所有li-希望这是有道理的。 A loop within a loop essentially.
本质上是一个循环内的一个循环。
As I understand it, you want to recreate what you've made with the django template in javascript. 据我了解,您想重新创建使用javascript中的django模板所做的工作。
As you're using jQuery this should work: 当您使用jQuery时,它应该可以工作:
// 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('');
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.