[英]How to disable function executing in bind method?
I've three simple functions 我有三个简单的功能
var loadPoints = function(successCallback, errorCallback) {
$.ajax({
method: 'get',
url: '/admin/graph/get-points',
dataType: 'json',
success: successCallback,
error: errorCallback
});
}
var successLoadPoints = function(points){
console.log('load ok');
//console.log(points);
// $.each(points,function(i, item){
// console.log(points[i]);
//
// });
}
var errorLoadPoints = function ()
{
console.log('error with loading points');
}
I bind function loadPoints to click event on button 我将函数loadPoints绑定到按钮上的click事件
$("button#viewPoints").bind(
'click', loadPoints(successLoadPoints,errorLoadPoints)
);
But function loadPoints is been executed without click event. 但是函数loadPoints已经执行而没有单击事件。 Why? 为什么? How to resolve this problem ? 如何解决这个问题?
Your current code is calling loadPoints
when you want to bind it, triggering the ajax request immediately. 当您想要绑定它时,您当前的代码正在调用 loadPoints
,立即触发ajax请求。
Your function should return a click handler function which will use the passed handlers for success and error. 您的函数应该返回一个单击处理函数,该函数将使用传递的处理程序来获得成功和错误。 This returned function will be called on click. 单击后将调用此返回的函数。
var loadPoints = function(successCallback, errorCallback) {
return function (event) {
$.ajax({
method: 'get',
url: '/admin/graph/get-points',
dataType: 'json',
success: successCallback,
error: errorCallback
});
};
}
$("button#viewpoints").on("click", loadPoints(successHandler, errorHandler));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.