简体   繁体   中英

Bind function( with parameters) to click event with Jquery

This works:

HTML:

<div id="mydiv">Help!</div>

CSS:

div {
    background-color: red;
}

Jquery:

function myfunction( c1 ) {
    $("#mydiv").css({'background-color': 'blue' });
}

$("#mydiv").on('click',  myfunction );

I understand that using () immediately after a function calls that function.

So...

How can I bind a function to a click, and pass parameters at the same time?

HTML:

<div id="mydiv">Help!</div>

CSS:

div {
    background-color: red;
}

Jquery:

function myfunction( c1 ) {
    $("#mydiv").css({'background-color': c1 });
}

$("#mydiv").on('click',  myfunction("blue") );

您可以将调用包装在函数表达式中,并使用call方法将调用的上下文设置为事件处理程序中的上下文:

$("#mydiv").on('click', function(){ myfunction.call(this, "blue"); });

The jquery on event binding function has a 'data' parameter. .on( events [, selector ] [, data ], handler )

http://jsfiddle.net/aNDgC/101/

$('#myButton').on("click", {name: "world"} , function(event){
    $('#divOutput').html(event.data.name);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM