jQuery .click( foo() ) 意外行为
今天,我在我的网络应用程序中遇到了一个关于表单搜索提交功能(在 js 中)和 jQuery 中的按钮单击操作的错误。
我有一个附加了 submitEmpSearch()
操作的表单。它作为 onSubmit
操作嵌入在表单的 html 中。还有一个与带有 onclick
事件 submitEmpSearch()
的表单关联的搜索按钮。我试图从模板中清除嵌入的 javascript,以支持 jQuery 调用。在包含的 jQuery 调用中,我在 $(document).ready
组中调用了 $('#search-button').click(submitEmpSearch() )
。
根据我之前使用 .click()
函数的经验,我预计它具有与所提供的嵌入式 onclick
属性相同的功能。然而,相反,它给页面带来了一个无限循环(显然)在加载后立即单击按钮!
现在,以前,我总是传递一个 function() {}
模式。我以前从未传入过预定义函数。这是 jQuery 语言 框架中的某种陷阱吗?还是我做错了什么?
Today I came across a bug in my web app regarding form search submit function (in js) and a button click action in jQuery.
I have a form that has the action submitEmpSearch()
attached to it. This is embedded in the html of the form as it's onSubmit
action. There is also a search button associated with the form with an onclick
event submitEmpSearch()
. I was making an attempt to clear out embedded javascript from the templates in favor of jQuery calls. In an included jQuery call I had the call $('#search-button').click( submitEmpSearch() )
inside my $(document).ready
group.
From my previous experience with the .click()
function, I expected this to have the same functionality as the embedded onclick
attribute provided. However, instead, it gave the page an infinite loop of (apparently) clicking the button as soon as it loaded!
Now, previously, I always passed a function() {}
pattern. I had never passed in a predefined function before. Is this some kind of gotcha in the jQuery language framework? Or is there something else I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
jQuery不是一种语言。 javascript 是语言。您要传递函数的结果,当您要传递函数本身时:
应该是:
在JavaScript中,函数可以作为值传递。但是,
submempsearch()
是呼叫对函数的返回值,就像人们对其他语言的期望一样。jQuery is not a language. JavaScript is the language. You're passing the result of the function, when you want to pass the function itself:
It should be:
In JavaScript, functions can be passed as values. However,
submitEmpSearch()
is the return value of a call to the function, as one would expect from other languages.而不是仅
使用
或
如果“搜索按钮”是一个类,则必须添加“.”, 此外。 (点)之前。如果是 id 则必须添加“#”。
看我的例子。
Instead of
use just
or
Also if the 'search-button' is a class you have to add a "." (dot) before it. If it is an id you have to add "#".
See my examples.
啊哈!
您应该通过引用传递函数,而不是调用函数并传递其结果:
Aha!
You should pass the function by reference, not call the function and pass its result:
更改为
:
这种方式不是执行submitEmpSearch() 并将其返回值传递给click(),而是将委托传递给click()。
Change from:
to:
This way instead of executing submitEmpSearch() and passing its return value to the click(), you're passing the delegate to the click().
试试这个。
Try this.