简体   繁体   English

绑定函数(带有参数)以使用jQuery单击事件

[英]Bind function( with parameters) to click event with Jquery

This works: 这有效:

HTML: HTML:

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

CSS: CSS:

div {
    background-color: red;
}

Jquery: 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: HTML:

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

CSS: CSS:

div {
    background-color: red;
}

Jquery: 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. 事件绑定函数上的jQuery具有“数据”参数。 .on( events [, selector ] [, data ], handler ) .on(事件[,选择器] [,数据],处理程序)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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