2015-08-27 207 views
2

所以,问题是我有一个事件侦听器和一个功能:如何将参数传递给由事件处理程序触发的函数?

$(document).ready(function() { 

    function insert_hint(element, string){ 
     console.log(string); 
    } 

    $('.test').on('click', insert_hint('123', '123')); 

}); 

,但如果我不喜欢这样,它会立即触发我的功能,而不是等待与类“测试”的元素被点击。

如何防止它发生,以及将参数传递给正在事件上触发的函数的正确方法是什么?

我有一种感觉,这是非常明显和容易的事情,但我只是想念它。

+6

包装在另一个函数。 – Pointy

+1

为什么你会花时间写这个问题,而不是只在谷歌输入标题,已经有成千上万的答案? -1 – 1252748

回答

11

你可以简单地这样做:

$('.test').on('click', function() { 
    insert_hint('123', '123'); 
}); 

薪火点击回调函数内的功能。

更多细节在这里:.on() jQuery API Documentation

+0

11对一个答案(它不使用正确的术语)提出了一个如此简单的问题,它本来不应该被问到......什么是SO来了! :) –

7

你需要用的功能到另一个功能,这将指定其的论点。

$(document).ready(function() { 

    function insert_hint(element, string){ 
     console.log(string); 
    } 

    $('.test').on('click', function() { 
     insert_hint('123', '123'); 
    }); 

}); 
6

包成像@palash匿名函数的外面@ralh证明,你也可以使用.bind()

()方法创建一个新的函数,调用它时,有其绑定将此关键字设置为提供的值,并在调用新函数时提供的任何前面给定的参数序列。

$(document).ready(function() { 

    function insert_hint(element, string, evt){ 
     console.log(element, string, evt); // "hello", "world", the click event 
    } 

    $('.test').on('click', insert_hint.bind(this, 'hello', 'world')); 

}); 

的jsfiddle:http://jsfiddle.net/8nahor6L/

相关问题