尝试传入回调函数失败

egi*_*dra 0 javascript jquery

我试图在用户点击网页上的元素时创建一些功能.一旦页面执行,回调函数就会执行.它只应在用户单击元素时执行.这是代码:

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

谢谢!

Al *_*l W 5

这实际上并没有传递函数,而是它正在评估函数并将结果作为回调参数传递(在本例中undefined).

试试这个

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