尝试在 JavaScript/jQuery 中添加点击事件

Trying to add an on click event in JavaScript/jQuery

我正在尝试制作一个“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
}

您必须将元素与事件绑定

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
}

您可以使用 on() 为动态创建的元素附加事件。然后在匿名函数内部调用函数,如下所示:

变化:

$(`day${i}`).click(showCard(date,i));

$('ul').on('click', `.day${i}`, function { showCard(date,i) });