English 中文(简体)
传递参数时,事件侦听器过早触发
原标题:Event listener firing too early when parameters are passed

我将多个参数传递给一个javascript函数,该函数构建一个表单供用户填写。在这些参数中,还有两个函数包含在一个单独的类中,用于处理表单的保存或取消。cancel函数需要两个参数来确定要构建的实体列表。问题在于参数。在表单构建功能中,如果我将取消功能附加到新创建的取消按钮上,而没有给它任何参数,则功能按钮工作正常,但由于缺乏参数,会构建一个空列表。但是,如果我将函数与参数附加在一起,则函数会在创建页面时立即触发,而不是在单击按钮时触发。我尝试过以几种不同的方式附加监听器,包括javascript、jquery甚至yahoo.util。当在其他情况下使用参数调用cancel函数时,它会正常工作。你知道为什么函数在传递参数时会提前触发吗?

以下是我附加偶数监听器的不同方式的sudo代码。

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);
}
最佳回答

你必须将方法调用封装在函数块中,否则它们会立即被求值:

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

暂无回答




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签