简体   繁体   English

为什么jQuery .on('click',foo)为什么在页面加载而不是click上运行函数?

[英]Why does jQuery .on( 'click', foo ) run the function on page load and not on click?

Below is a simple example of what i'm running into. 以下是我遇到的一个简单示例。

All I want to do is add an event handler for the function Foo to link1 so that when link1 is clicked it will run Foo. 我要做的就是将Foo函数的事件处理程序添加到link1,以便在单击link1时将运行Foo。

But what is happening is that Foo actually runs onpageload and never onClick of link1. 但是实际情况是,Foo实际上在onpageload上运行,而从不在link1的onClick上运行。

What's going on? 这是怎么回事?

 $(document).ready(function(){ $( '#link1' ).on( 'click', foo( 'hello' ) ); }); function foo( bar ){ alert( bar ); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#" id="link1">hello</a> <a href="#" id="link2">world</a> 

You need to pass a function reference as the click handler, you are invoking the function(By adding () at the end of function) so the function is executed first then the value returned by it( undefined in this case as the event handler.) 您需要传递一个函数引用作为点击处理程序,然后调用该函数(通过在函数末尾添加() ),以便先执行该函数,然后再执行该函数返回的值(在这种情况下, undefined为事件处理程序)。 )

One solution here, since you want to pass a custom argument to the called function is to use a anonymous function as the event handler which will call foo with desired parameter 这里的一种解决方案是,由于您要将自定义参数传递给被调用的函数,因此需要使用匿名函数作为事件处理程序,该事件处理程序将使用所需参数调用foo

 $(document).ready(function() { $('#link1').on('click', function() { foo('hello') }); }); function foo(bar) { alert(bar); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#" id="link1">hello</a> <a href="#" id="link2">world</a> 


Update if you don't want to pass any custom parameters to the target function foo then 如果您不想将任何自定义参数传递给目标函数foo,则更新

 $(document).ready(function() { $('#link1').on('click', foo); }); function foo(event) { alert('foo called'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#" id="link1">hello</a> <a href="#" id="link2">world</a> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM