开发者

Trying to pass in a callback function fails

开发者 https://www.devze.com 2023-03-22 10:44 出处:网络
I am trying to create some functionality when a user clicks on an element on the webpage. The callback function executes as soon as the page is executed. It is only supposed to execute when the user c

I am trying to create some functionality when a user clicks on an element on the webpage. The callback function executes as soon as the page is executed. It is only supposed to execute when the user clicks on an element. Here is the code:

<!DOCTYPE html>
<html>
  <head>
    <title>Javascript Test</title>
    <script src="http://code.jquery.com/jquery-latest.pack.js"></script>
    <script>
   开发者_JS百科   $("#clickMe").one('click', printThis("Hello All"));
      function printThis(msg) {
        console.log(msg);
      }
    </script>
  </head>
  <body>
    <div id="clickMe">Click me!</div>
  </body>
</html>

Thanks!


That isn't actually passing the function, but instead it is evaluating the function and passing the result as the callback parameter (in this case, undefined).

Try this instead

<script>
  function printThis(msg) {
    console.log(msg);
  }
  $("#clickMe").one('click', function() {
     printThis("Hello All");
  });
</script>


Don't invoke the callback. Pass an anonymous callback function that invokes the function you want.

function printThis(msg) {
    console.log(msg);
}

$("#clickMe").one('click', function() { printThis("Hello All") });


one method takes a callback as the second parameter. printThis("Hello All") will actually call the method there itself so on click of clickMe nothing will happen as there is no handler attached. Try this

function printThis(msg) {
    console.log(msg);
}

$("#clickMe").one('click', function() { printThis("Hello All") });


The answer already posted is right:

$("#clickMe").one('click', function() { printThis("Hello All") });

This is known as a closure: https://developer.mozilla.org/en/JavaScript/Guide/Closures A closure is a function, often declared as an inline/anonymous block of code, that delays the execution of your function and stores the value of that "Hello All" argument that you want to pass in.

jQuery will store this "function() {...}" code block as an event handler, and then later when the #clickMe element is clicked, that code block will be executed, which in turn will call the printThis function.

You will find yourself using this pattern quite often with jQuery.


Try this ... http://jsfiddle.net/PcVJq/

0

精彩评论

暂无评论...
验证码 换一张
取 消