简体   繁体   中英

How to pass an anonymous function to Jquery's click handler

I have a piece of code making use of Jquery's click() event handler below.

 //advance automaton by one step $('#nextstep').click(function() { if (canAdvanceAutomaton) { runAutomaton(logicalGrid); } }); 

I thought that .click() accepts an anonymous function, so I tried changing my code to the one below.

 //advance automaton by one step $('#nextstep').click = () => { if (canAdvanceAutomaton) { runAutomaton(logicalGrid); } }; 

I believed these two pieces of code would be equivalent, but it turns out the latter version doesn't run my canAdvanceAutomaton function when I click the html id with #nextstep , and I don't see any errors in the console. Can anyone tell me why these two ways of calling .click() are not equivalent?

Both codes are using anonymous functions, but in the second, you're trying to assign to the click property, when you should be passing the arrow function to the .click method :

$('#nextstep').click(() => {
  if (canAdvanceAutomaton) {
    runAutomaton(logicalGrid);
  }
});

Two things:

  1. Your first function is anonymous. Your second one is also anonymous. The only difference between them is that the first is a traditional function and the second is an arrow function (which doesn't have its own this binding). More about the various different forms of functions (named and anonymous) in this answer .

  2. The problem with your second thing is you're not calling click , you're assigning to click .

If you pass an arrow function into click , it'll work, but this within the function won't be the element that was clicked. (You can still get it from currentTarget on the event object it receives, though.)

$('#nextstep').click((e) => {
    // You can use `e.currentTarget` to know which was clicked
    if (canAdvanceAutomaton) {
        runAutomaton(logicalGrid);
    }
});

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