为什么我的点击处理程序已经在文档上运行了

Why is my click handler being run on document ready?

本文关键字:文档 运行 我的 处理 程序 为什么      更新时间:2023-09-26

好吧,我已经为div点击设置了一个处理程序,但由于某种原因,它在document.ready上触发,我真的不知道为什么。这是我的代码:

function statusCallback(status){
    //THIS IS THE JSONP CALLBACK RECEIVED FROM THE SERVER
    if(status.title==null){
        $('#core').attr('class','play');
        $('#button').animate({marginLeft:'350px'},2000,'easeOutCubic',function(){
            $('#button').click(initialBinder());
        });
    }else{
    }
}
function initialBinder(){
    $('#button').unbind('click');
    $('#core').attr('class','load');
    $('#button').animate({marginLeft:'0px'},2000,'easeOutCubic',function(){
        $.ajax({
            url:'http://24.182.211.76/status.php',
            crossDomain:true,
            dataType:'jsonp'
        });
    });
}
$(document).ready(function(event){
    $('#button').click(initialBinder());
});

更改:

$('#button').click(initialBinder());

至:

$('#button').click(initialBinder);

前者实际上会调用函数,而不是返回指向它的函数指针。

也许这一点点代码可以澄清差异:

function foo(x, y) //I'm function foo, I add two numbers like a boss
{
   return x + y;
};
var x = foo(1,1); //x is 2 because we called the function
var y = foo; //y is a reference to function foo, no parentheses
var z = y(1,1); //z is 2 because we called foo through reference y
document.write('x = ' + x + '<br />z = ' + z);

$('#button').click(initialBinder);

您没有将函数引用为回调,而是调用了一个函数。

尝试从绑定语句中删除parens,如下所示:

$(document).ready(function(event){
    $('#button').click(initialBinder);
});

实际情况是,函数正在被执行,而不是作为参数传递。