在jquery中使用on()时传递params来起作用

时间:2016-06-02 03:37:00

标签: javascript jquery

我的一位大四学生建议我总是使用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?
} 

1 个答案:

答案 0 :(得分:4)

您可以使用下面的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>
&#13;
&#13;
&#13;

如果您想知道是否可以直接执行此操作:

 $(".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.