javascript - 在 jquery 中使用 on() 时将参数传递给函数

标签 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?
} 

最佳答案

您可以使用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/

相关文章:

javascript - TransitionEnd 触发太早

javascript - jQuery CSS 不工作但 Animate 是

javascript - select2 不加载 ajax 数据 : TypeError: c. ajax 不是函数

javascript - Datatables JS - 禁用特定列排序的 HTML5 方法?

javascript - 让 JS 函数执行简单的 AJAX true/false 请求并返回结果的最佳方法是什么

php - textarea 不显示 IE 但正在提交

javascript - 使用 jquery 在 svg 中选择图像

javascript - 这种排序可以更优雅/递归吗

javascript - 如何将表单数据发布为 JSON?

javascript - Angular 应用程序客户端缓存