javascript - Pass params to function when using on() in jquery -
a senior of mine advise me write using snytax 2, have issue passing parameters. if function coloring has 2 params, how pass them in?
//snytax 1 $("body").on("li","click",function(){ $(this).css({'color:red'}); }); //snytax 2 $("body").on("li","click", coloring); function coloring(param1,param2){ //what here? }
you can use event.data
below:
sample code:
$(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>
in case wondering if can directly this:
$(".btn").on("click", callme(a,b)); // call function when event bound. so, without click function invoked.