我正在尝试在JS中创建日历/日程表,并且在预定事件上使用的方法addEventListener
返回相同的事件ID,此时它应返回所单击事件的id。
这是我目前的功能:
monthStart = date.clone().subtract(1, 'months').endOf 'month'
monthEnd = parseInt date.clone().endOf('month').format 'DD'
daysContainer = @createElement 'div', 'calendar__days'
for i in [1..monthEnd]
day = monthStart.add 1, 'day'
current = day.format 'DD-MM-YYYY'
line = @createElement 'div', 'calendar__line'
line.classList.add 'line--today' if current == @current.format 'DD-MM-YYYY'
header = @createElement 'div', 'line__header'
header.appendChild @createElement 'h1', 'line__date', day.format 'DD'
header.appendChild @createElement 'span', 'line__day', day.format 'dd'
events = @createElement 'div', 'line__events'
events_data = @parseEventsPerDay current
for event in events_data
event_block = @createElement 'div', 'event'
x = event.id
event_block.addEventListener 'click', => console.log event.id <<---------- this line returns always the same id
event_container = @createElement 'div', 'event__container'
event_block.appendChild @createElement 'div', 'event__bbg' + ' ' + @resolveColor 'bg', event.type
event_container.appendChild @createElement 'div', 'event__timeinterval', event.timeStart + ' - ' + event.timeEnd
event_container.appendChild @createElement 'div', 'event__content' + ' ' + @resolveColor('link', event.type), event.title
event_block.appendChild event_container
events.appendChild event_block
line.appendChild events
line.appendChild header
line.appendChild events
daysContainer.appendChild line
@el.appendChild daysContainer
欢迎任何关于整个项目的想法,技巧,教程以及我的代码。
答案 0 :(得分:0)
正如@robiseb在注释中提到的,你需要使用闭包来确保当前事件是循环闭包内的局部变量,而不是全局变量。
有关闭包的详细信息,see this question。
Coffeescript为我们提供了do
关键字,以简化这一过程。请参阅loops and comprehensions coffee docs。
for event in events_data
do(event) ->
event_block = @createElement 'div', 'event'
x = event.id
event_block.addEventListener 'click', => console.log event.id
.
.
.