我的一位前辈建议我始终使用 snytax 2 进行编写,但我在传递参数方面遇到了一些问题。如果我的函数着色有 2 个参数,我如何传递它们?
//snytax 1
$("body").on("li","click",function(){
$(this).css({'color:red'});
});
//snytax 2
$("body").on("li","click", coloring);
function coloring(param1,param2){
//what to do here?
}
最佳答案
您可以使用event.data
,如下所示:
示例代码:
$(document).ready(function() {
$(".btn").on("click", {
a: 1,
b: 2
}, callme);
});
function callme(event) {
var data = event.data;
alert(data.a)
alert(data.b)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn">Click me!</button>
如果您想知道是否可以直接执行此操作:
$(".btn").on("click", callme(a,b)); // This would call the function when the event is bound. So, even without the click the function is invoked.
关于javascript - 在 jquery 中使用 on() 时将参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37582203/