문제

I am trying to use windows.addEventListener to execute my function on clicking a div. However nothing is happening.

This is my code:

Javascript:

window.addEventListener('load', init);

function init(){
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById("wheelContainer").addEventListener("onclick", function() { winPrize;
        }, false);
    });
}

Can someone please tell me what am I doing wrong.

Thankyou.

도움이 되었습니까?

해결책

There are at least three things wrong here:

  1. The event name for use with addEventLisener() is "click", not "onclick".
  2. You should use the window load event OR the DOMContentLoaded event, but not both.
  3. Your click handler function isn't actually doing anything. Did you mean to call a function like winPrize();?

So, cleaning all of those issues, you would have this:

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("wheelContainer").addEventListener("click", function() { winPrize();
    }, false);
});

You don't need the init() function or the window load event handler at all since you can just install the event handler when the DOMContendLoaded event fires.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top