简体   繁体   中英

Why does my JavaScript function see a mouseevent instead of an empty variable?

I'm attaching an eventlistener to a button on a page. When clicked, it runs a function.

harvestDataBtn.addEventListener("click", harvestData, false);

The function optionally takes a value.

function harvestData(idsToHarvest)

I don't want the clicking of the button to pass anything into the function. The optional variable idsToHarvest is used in other instances of the function being called, separate from the click.

However, when I click the button, idsToHarvest is a mouseevent. Making this code below inside my function not work as intended.

if ( idsToHarvest ) {
  // do something with string
} else {
  // button was clicked, do something else
}

您可以向事件侦听器传递一个函数,该函数包装对期望的harvestData调用,并忽略默认情况下传递的事件对象:

harvestDataBtn.addEventListener("click", function (e){harvestData();}, false);

el.addEventListener("click", function (event){ ... });

The 2nd param, in this case, a function, expects the argument passed in to be the event object.

If you are using that same function for other purposes and expect the argument to be something else, it won't work as an event handler.

From the spec , it states:

An event listener consists of these fields:

  • type (a string)
  • callback (an EventListener )
  • capture (a boolean, initially false)
  • passive (a boolean, initially false)
  • once (a boolean, initially false)
  • removed (a boolean for bookkeeping purposes, initially false)

As stated, it shows the callback is actually an EventListener , which is defined by the interface shown:

callback interface EventListener {
    void handleEvent(Event event);
};

As you can see, when the callback is evaluated and the handleEvent is called, it accepts 1 argument, event of the type Event .

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