如何将参数传递给JavaScript中的匿名函数? [英] How can I pass arguments to anonymous functions in JavaScript?

查看:82
本文介绍了如何将参数传递给JavaScript中的匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图弄清楚如何将参数传递给JavaScript中的匿名函数。

I'm trying to figure out how to pass arguments to an anonymous function in JavaScript.

查看此示例代码,我想你会看到我的意思:

Check out this sample code and I think you will see what I mean:

<input type="button" value="Click me" id="myButton" />

<script type="text/javascript">
    var myButton = document.getElementById("myButton");
    var myMessage = "it's working";
    myButton.onclick = function(myMessage) { alert(myMessage); };
</script>

点击按钮时,消息:正在运行应该出现。但是匿名函数中的 myMessage 变量为null。

When clicking the button the message: it's working should appear. However the myMessage variable inside the anonymous function is null.

jQuery使用了很多匿名函数,是什么传递该论点的最佳方法是?

jQuery uses a lot of anonymous functions, what is the best way to pass that argument?

推荐答案

您的具体案例可以简单地更正为有效:

Your specific case can simply be corrected to be working:

<script type="text/javascript">
  var myButton = document.getElementById("myButton");
  var myMessage = "it's working";
  myButton.onclick = function() { alert(myMessage); };
</script>

此示例将起作用,因为创建并指定为元素处理程序的匿名函数将可以访问变量在创建它的上下文中定义。

This example will work because the anonymous function created and assigned as a handler to element will have access to variables defined in the context where it was created.

对于记录,处理程序(通过设置onxxx属性分配)需要单个参数,即传递的事件对象通过DOM,你不能强制传递其他参数

For the record, a handler (that you assign through setting onxxx property) expects single argument to take that is event object being passed by the DOM, and you cannot force passing other argument in there

这篇关于如何将参数传递给JavaScript中的匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆