[英]passing arguments to click function in jquery fires the function without clicking
Hi I have a function that makes ajax calls once an element is clicked. 嗨,我有一个函数,一旦单击一个元素,就会进行ajax调用。 I use this code:
我使用以下代码:
$(document).ready(function()
{
function ajax_call(offset, length) {
$.ajax({method: "get",
url: "file.php",
data: "offset="+ offset,
success: function(returnedData)
{
$("#content").html(returnedData);
}
});
}
$("#profile").click(ajax_call(0, 1000));
});
The issue is with this line: 问题在于此行:
$("#profile").click(ajax_call(0, 1000));
When I pass arguments to ajax_call function, the function is run once the page loads without any user intervention, however when I remove the arguments like this: $("#profile").click(ajax_call);
当我将参数传递给ajax_call函数时,页面加载后将运行该函数,而无需任何用户干预,但是当我删除这样的参数时:
$("#profile").click(ajax_call);
the function is called only when the element is clicked. 仅在单击元素时才调用该函数。 I have researched for hours about this issue but with no luck
我已经研究了几个小时,但是没有运气
This will call the function immediately ajax_call(0, 1000)
and pass the return value as event handler. 这将立即调用该函数
ajax_call(0, 1000)
并将返回值作为事件处理程序传递。
You have to wrap it in an anonymous function: 您必须将其包装在匿名函数中:
$("#profile").click(function() {
ajax_call(0, 1000);
});
Whenever you have functionname()
you are actually calling the function. 每当您具有
functionname()
您实际上就是在调用该函数。 functionname
instead (without parenthesis) gives you a reference to the function. 相反,
functionname
(不带括号)为您提供了对该函数的引用。 As you cannot just pass ajax_call
to click
, you have to wrap it in another function. 由于您不能仅将
ajax_call
传递给click
,因此必须将其包装在另一个函数中。
So the anonymous function function(){...}
is passed as event handler and when it gets called, it executes ajax_call(0, 1000)
. 因此,匿名函数
function(){...}
作为事件处理程序传递,并在调用它时执行ajax_call(0, 1000)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.