2012-01-28 5 views
2

さて、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()); 
}); 

答えて

10

は変更:

$('#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);

+0

私にそれを打ち明けなさい:( – Aaron

+0

働いた!それを知らなかった。ありがとう! – nkcmr

+1

@Tegeril - はい私は激しくタイプしていた!:) –

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

おそらく、このコードの少しの違いを明確にすることができます。

0

このようなあなたのバインドのステートメントから括弧を削除してください:

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

何が起こっている関数が実行されたばかりではなく、引数として渡されているということです。

関連する問題