为什么在使用点击事件处理程序时执行非匿名函数? [英] Why are non-anonymous functions being executed when using click event handler?

查看:124
本文介绍了为什么在使用点击事件处理程序时执行非匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在探索使用自定义函数来处理事件处理程序。在这个简单的例子中,我试图在用户点击一个按钮时弹出一个提示。

I've been exploring the use of custom functions for event handlers. In this stripped down example, I'm trying to get an alert to pop up when the user clicks a button.

但是,当页面加载时,警告框会立即弹出!我究竟做错了什么? (注释的部分完全相同)

But the alert box pops up immediately as the page loads! What am I doing wrong? ( the commented portion does the exact same thing).

如果我定义bclick()函数,如

If I define the bclick() function like

function bclick(foo, bar){ ... }

结果也是一样的。

标题中的JS:

<script type="text/javascript">

var bclick = function(foo, bar){alert( foo + "  " + bar + "\n");}

//$(document).ready(function(){
//    $("button").click(bclick("Button","Clicked"));
//    });

$("button").click(bclick("Button","Clicked"));

</script>

正文中的相关HTML:

Relevant HTML in the body:

<button>Click Me!</button> 


推荐答案

您在评估您的功能之前,甚至通过它。

You're evaluating your function before you even pass it.

$("button").click(bclick("Button","Clicked"));

这里,使用这些参数调用 bclick ,而结果正在传递给点击方法。你想像普通变量一样传递它,如下所示:

Here, bclick is called with those arguments, and the result is being passed to the click method. You want to pass it like a normal variable, like this:

$("button").click(bclick);

然而,显而易见的问题是您无法传入自定义参数。

The obvious problem with this, though, is the fact that you can't pass in custom arguments.

您还可以传入一个调用函数的匿名函数:

You could also pass in an anonymous function that calls your function:

$("button").click(function() { bclick("Button", "Clicked"); });

这篇关于为什么在使用点击事件处理程序时执行非匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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