传递参数时事件监听器过早触发 [英] Event listener firing too early when parameters are passed

查看:113
本文介绍了传递参数时事件监听器过早触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一些参数传递给一个javascript函数,该函数构建一个供用户填写的表单。这些参数中包含另外两个函数,它们处理表单的保存或取消。 cancel函数需要两个参数来确定要构建的实体列表。问题在于参数。在表单构建功能中,如果我将取消功能附加到新创建的取消按钮而不给它任何参数,则功能按钮工作正常但由于缺少参数而构建空列表。但是,如果我使用参数附加函数,则在创建页面时立即触发该函数,而不是在单击按钮时触发。我尝试以几种不同的方式附加监听器,包括javascript,jquery甚至yahoo.util。在其他实例中使用参数调用时,取消函数中的所有内容都能正常工作。关于为什么函数在参数传递时会提前触发的想法?

I pass a number of parameter to a javascript function which builds a form for the user to fill in. Among these parameters are two more functions contained in a separate class which handle the saving or canceling of the form. The cancel function requires two parameters which it uses to determine which list of entities to build. The problem lies in the parameters. While in the form building function, if I attached the cancel function to the newly created cancel button without giving it any parameter the function button works fine but builds an empty list due to the lack of parameters. However if I attach the function with the parameters, the function fires right away when the page is created rather than when the button is clicked. I have tried attaching the listener in a couple different ways including javascript, jquery and even yahoo.util. Everything works correctly in the cancel function when it is called with parameters in other instances. Any ideas on why the function fires to early when parameters are passed?

这是一些sudo代码,其中包含了我连接偶数监听器的不同方法。

Here is some sudo code of different ways I have attached the even listener.

function buildform(formData, saveFunction, CancelFunction, p1, p2){
      $("#cancelButton").live("click", cancelFunction(p1, p2);
      YAHOO.util.Event.on("cancelButton", "click", cancelFuntion(p1, p2));
      cancelButton.setAttribute("onClick",cancelFunction(p1, p2);
}


推荐答案

你有将函数块中的方法调用包装起来,否则会立即对它们进行求值:

You have to wrap your method calls in function blocks, otherwise they are evaluated immediately:

$("#cancelButton").live("click", function () { cancelFunction(p1, p2); });

这篇关于传递参数时事件监听器过早触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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