简体   繁体   中英

How properly add event using addEventListener?

I'm trying to add a click-event to div element, but it doesn't work.

Link to js file is under body tag so element divContainer already exists. I tried to add div-element using appendChild and add event to it in browser console and it worker.

I didn't want to add full code, but here it is. I just don't understand why addEventListener doesn't work here.

         function DatePicker(id, callback) {
    let monthNames = ["January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
    ];

    this.render = function (date) {
        let divContainer = document.getElementById(id);
        let selectedDay = date.getDay() !== 0? date.getDay() : 7;

        let prevMonth = new Date(date.getFullYear(), date.getMonth(), 1 - selectedDay);
        let month = new Date(date.getFullYear(), date.getMonth(), 1);
        let nextMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0);
        let firstDayInMonth = month.getDay() !== 0? month.getDay() : 7;
        let lastDayInMonth = nextMonth.getDay() !== 0? nextMonth.getDay() : 7;

        divContainer.innerHTML = '';
        divContainer.innerHTML +=
            '<div class="header"><div class="triangle-left" onclick="goPrev(this.parentElement)"></div>' +
            monthNames[date.getMonth()] + ' ' + date.getFullYear() +'<div class="triangle-right" onclick="goNext(this.parentElement)"></div></div>';

        divContainer.innerHTML +=   '<div><a>Mon</a> <a>Tue</a> ' +
                                    '<a>Wed</a> <a>Thu</a> <a>Fri</a>' +
                                    '<a>Sat</a> <a>Sun</a></div><hr>';

        for(let i = 0; i < firstDayInMonth - 1; ++i)
        {
            divContainer.innerHTML += '<div class="anotherMonth"  onclick="goPrev(this)">'+(prevMonth.getDate() + 1 + i)+'</div>';
        }
        for(let i = 0; i < nextMonth.getDate(); ++i)
        {
            if((i+1) === date.getDate()) {
                let div = document.createElement('div');
                div.classList.add('selectedDate');
                div.innerText = 1+i;
                divContainer.appendChild(div);
                div.addEventListener("click", function(){ alert("Hello World!");});
            }
            else {
                let div = document.createElement('div');
                div.classList.add('currentMonth');
                div.innerText = 1+i;
                divContainer.appendChild(div);
                div.addEventListener("click", function(){ alert("Hello World!"); });
            }
        }
        for(let i = 0; i < 7 - lastDayInMonth; ++i)
        {
            divContainer.innerHTML += '<div class=\"anotherMonth\"  onclick="goNext(this)">'+(1 + i)+'</div>';
        }
    };
}

As long as you pass a valid id into .getElementById() and that element has already been parsed into the DOM, the code will work:

 // You must pass a string with a valid id let divContainer = document.getElementById("container"); for(let i = 0; i < 10; ++i) { let div = document.createElement('div'); div.classList.add('selectedDate'); div.textContent = 1+i; // Use textContent. innerText is non-standard div.addEventListener("click", function(){ alert("Hello World!"); }); divContainer.appendChild(div); // Append last for better performance in many cases } 
 <div id="container"></div> 

Your code, when referencing an existing element, works just fine:

 let divContainer = document.getElementById('existing'); for(let i = 0; i < 10; ++i) { let div = document.createElement('div'); div.classList.add('selectedDate'); div.innerText = 1+i; divContainer.appendChild(div); div.addEventListener("click", function(){ alert("Hello World!"); }); } 
 <div id="existing"></div> 

But it is best to only use click handlers on <button> , <a> and <input> elements to improve the ability of a screen reader working correctly with your site.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM