質問

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