如何使用addEventListener正确添加事件?

时间:2019-04-19 18:53:19

标签: javascript dom addeventlistener dom-events

我正在尝试向div元素添加点击事件,但是它不起作用。

到js文件的链接在body标签下,因此元素divContainer已存在。我试图使用appendChild添加div-element并在浏览器控制台及其工作器中添加事件。

我不想添加完整的代码,但是就在这里。我只是不明白为什么addEventListener在这里不起作用。

         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>';
        }
    };
}

2 个答案:

答案 0 :(得分:0)

只要您将有效的id传递到.getElementById()且该元素已经被解析到DOM中,代码就会起作用:

// 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>

答案 1 :(得分:0)

您的代码在引用现有元素时可以正常工作:

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>

但是最好仅在click<button><a>元素上使用<input>处理程序,以提高屏幕阅读器与您的网站正确配合的能力。 / p>