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
Add a ment  | 

3 Answers 3

Reset to default 11

You 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/

本文标签: javascriptHow to pass parameters to a function that is getting triggered by an event handlerStack Overflow