2012-11-17 64 views
2

我想激活一個警報,當我點擊登錄鏈接,出乎意料地沒有任何反應。 我需要一些幫助。jQuery的onClick沒有得到激活

我想要點擊登錄鏈接時彈出警告,但令人驚訝的是沒有任何反應。 感謝, 米克

<!DOCTYPE html> 
<html> 
<head> 
<title>Facebook Client-side Authentication Example</title> 
<script src="jquery.js" type="text/javascript"></script> 

</head> 
<body> 

<div id="fb-root"></div> 
<script type="text/javascript"> 
    // want Alert to popup when I click on auth-loginlink 
$("#auth-loginlink").on("click",function() { 
    alert("hi hello"); 
}); 
// ultimately I would like this to be binded with login and logout link 
$("#auth-logoutlink").on("click", bindLogout); 

function bindLogin(event){ 
alert("hello"); 
//FB.login(); 
}; 

function bindLogout(event){ 
alert("Out !!!"); 
//FB.logout(); 
};  

</script> 
<h1>Facebook Client-side Authentication Example</h1> 
    <div id="auth-status"> 
    <div id="auth-loggedout"> 
     <a href="#" id="auth-loginlink">Login</a> 
    </div> 
    <div id="auth-loggedin" style="display:none"> 
     Hi, <span id="auth-displayname"></span> 
     (<a href="#" id="auth-logoutlink">logout</a>) 
    </div> 
    </div> 
</body> 
</html> 

回答

3

您的代碼在元素加載到頁面之前執行。

發生這種情況是因爲您的腳本位於HTML元素之上。

您需要在頁面底部移動腳本,或者在DOM準備就緒後以更健壯的方式調用它。

jQuery爲此提供了一種方法。

$(document).ready(function(){ 
// your code in here will be called after the DOM is ready 
}); 

$(function(){ 
    // your code in here will be called after the DOM is ready 
}); 

文檔的http://api.jquery.com/ready/

0

你必須使用:

$(function() { 
    //Your code here 
}) 

因爲這時代碼獲取頁面加載後執行。

0

一切都在JQuery的需要是內

$(document).ready(function() { 
}); 

除了函數定義。否則,你正試圖註冊一個處理程序到一些還不存在的東西。

0

問題的短版是您在<script>功能沒有必然的標記。 確保在文檔準備好時耦合JQuery函數。使用此結構:

$(document).ready(function(){ 
//Add your functions here. 
//Use the JQuery-Factory-function to construct JQuery-Objects, encapsulating the tag: 

$(SELECTOR).click(YOURFUNCTION); 

}); 

一個更強大的方法是做一個新的JS-文件與 「jQuery的用戶自定義碼」:

(function($){ 
$(document).ready(function(){ 

//Your own JQuery-Code 
}); 
})(jQuery);