0
我想在JS中創建一個日曆/日程表,並且在預定事件上使用的方法addEventListener
返回相同的事件ID,當它應該返回點擊事件的ID時。addEventListener不能按預期的方式工作在循環中
這是我此刻的功能:
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
而且任何意見,建議,爲整個項目的教程,對我的代碼,歡迎選購。
在'addEventListener'的循環中使用閉包。 [更多信息](http://stackoverflow.com/questions/3572480/please-explain-the-use-of-javascript-closures-in-loops) – Robiseb
@Robiseb我試過這個:(() - > console.log event.id)它沒有工作。 –