2012-01-28 36 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 2012-01-28 03:12:34

+0

工作!永遠不會知道這一點。謝謝! – nkcmr 2012-01-28 03:13:05

+1

@Tegeril - 是的,我打字憤怒!:) – 2012-01-28 03:13:50

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

你沒有引用一個函數作爲回調,但調用一個函數。

0

嘗試從您綁定的語句去掉括號這樣的:

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

發生了什麼事是,功能得到執行,而不是作爲一個參數傳遞。

相關問題