尝试传入回调函数失败

时间:2011-07-25 04:20:30

标签: 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>

谢谢!

5 个答案:

答案 0 :(得分:5)

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

试试这个

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

答案 1 :(得分:3)

不要调用回调。传递一个匿名回调函数,调用你想要的函数。

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

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

答案 2 :(得分:1)

一个方法将回调作为第二个参数。 printThis(“Hello All”)实际上会在那里调用方法,所以点击clickMe就不会发生任何事情,因为没有附加处理程序。试试这个

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

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

答案 3 :(得分:1)

已经发布的答案是对的:

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

这称为闭包:https://developer.mozilla.org/en/JavaScript/Guide/Closures 闭包是一个函数,通常被声明为内联/匿名代码块,它会延迟函数的执行并存储您想要传入的“Hello All”参数的值。

jQuery会将这个“function(){...}”代码块存储为事件处理程序,然后在单击#clickMe元素时,将执行该代码块,进而调用printThis函数

你会发现自己经常使用jQuery这个模式。

答案 4 :(得分:0)

试试这个...... http://jsfiddle.net/PcVJq/