简体   繁体   中英

How to get the mouse event of a mousedown event when I pass a parameter

    let bob = 'hello';
    
    document.addEventListener('mousedown', dragStart(event))
    
    let dragStart = function (event) {
      console.log(event) // undefined
    }

Here is some code, the event is equal to undefined, but how can I have it equal to the mouse event (so that I can get the target of the click)?

This is because you are not passing a reference to a function as you set it up, you are invoking your dragStart() function immediately and the return value from it (which is nothing/undefined) is what is actually being used for the callback function reference. So, when the event actually does occur, nothing happens.

There is also no real reason to pass the bob argument to the function as it is declared as a Global variable, so it's accessible from anywhere.

You can wrap your call to your function with an anonymous function that you pass to .addEventListener() :

 let bob = 'hello'; document.addEventListener('mousedown', function(event){dragStart(event)}) let dragStart = function (event) { console.log(bob, "The " + event.type + " event was triggered."); }

Or, if you will only ever need the dragStart function as a callback to this event, you can pass the entire function into .addEventListener() instead of wrapping the call for it in another function:

 let bob = 'hello'; document.addEventListener('mousedown', function(event){ console.log(bob, "The " + event.type + " event was triggered."); });

And, if you want to make it even more concise, you can use " arrow function " syntax:

 let bob = 'hello'; document.addEventListener('mousedown', (event) => { console.log(bob, "The " + event.type + " event was triggered."); });

You have to wrap the calling of the function into an arrow function (or any sort of function really)

let bob = 'hello';

document.addEventListener('mousedown', (event) => dragStart(event, bob))

let dragStart = function (event, bob) {
  console.log(event, bob)
}

You are not passing a method to your event listener. Do this instead:

    let bob = 'hello';
    
    document.addEventListener('mousedown', event => dragStart(event))
    
    let dragStart = function (event) {
      console.log(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