我正在尝试创建一个“for”循环,在日历中为每一天添加一个函数,在单击时会构建一张卡片,其中包含当前单击的课程描述。
我的问题是,它构建了我加载日历的第二个月中所有日期的所有卡片,而无需等待我点击特定元素。
这是我的代码中与此问题相关的一部分
for(let i=1;i<=numberOfDays;i++){ //go through all days and building them in a calendar
$(`ul.days`).append(`
<li class="day${i}">${i}</li>
`)
lessons(date,i); //this just mark the days that have lessons in them
$(`day${i}`).click(showCard(date,i)); //for each day adds a function
}
您可以使用on()
为动态创建的元素附加事件。然后调用匿名函数内部的函数,如下所示:
更改:
$(`day${i}`).click(showCard(date,i));
至
$('ul').on('click', `.day${i}`, function { showCard(date,i) });
您必须将元素与事件绑定
for(let i=1;i<=numberOfDays;i++){ //go through all days and building them in a calendar
$(`ul.days`).append(`
<li class="day${i}">${i}</li>
`)
lessons(date,i); //this jsut mark the days taht have lessons in them
$(`day${i}`).bind( "click", function() {showCard(date,i)}); <--//for each day adds a function
}