admin管理员组文章数量:1356332
So the problem is I have an event listener and a function:
$(document).ready(function() {
function insert_hint(element, string){
console.log(string);
}
$('.test').on('click', insert_hint('123', '123'));
});
But If I do it like this, it instantly triggers my function, instead of waiting for the element with class 'test' to be clicked.
How can I prevent it from happening and what is a proper way to pass parameters to a function that is being triggered on an event?
I have a feeling that it's something very obvious and easy, but I'm just missing it.
So the problem is I have an event listener and a function:
$(document).ready(function() {
function insert_hint(element, string){
console.log(string);
}
$('.test').on('click', insert_hint('123', '123'));
});
But If I do it like this, it instantly triggers my function, instead of waiting for the element with class 'test' to be clicked.
How can I prevent it from happening and what is a proper way to pass parameters to a function that is being triggered on an event?
I have a feeling that it's something very obvious and easy, but I'm just missing it.
Share Improve this question asked Aug 27, 2015 at 14:49 TachiTachi 2,2323 gold badges29 silver badges44 bronze badges 2- 6 Wrap it in another function. – Pointy Commented Aug 27, 2015 at 14:50
- 1 Why would you spend time writing this question instead of just typing the title into google where there are already thousands of answers to it? -1 – 1252748 Commented Aug 27, 2015 at 14:53
3 Answers
Reset to default 11You can simply do this:
$('.test').on('click', function() {
insert_hint('123', '123');
});
Passing the function inside the click callback function.
More details here: .on() jQuery API Documentation
You need to wrap the function into another function, which will specify its' arguments.
$(document).ready(function() {
function insert_hint(element, string){
console.log(string);
}
$('.test').on('click', function() {
insert_hint('123', '123');
});
});
Outside of wrapping it into an anonymous function like @palash and @ralh demonstrated, you can also use .bind()
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
$(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/8nahor6L/
版权声明:本文标题:javascript - How to pass parameters to a function that is getting triggered by an event handler? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743997466a2573254.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论