2012-09-20 55 views
0

我在這裏丟失了什麼?使用jquery對標籤的點擊事件採取行動

<script type="text/javascript" src="static/js/jquery-1.7.2.js"></script> 
     <script> 

       $("a").click(function() { 
        alert("Handler for .click() called."); 
        window.location.reload(); 
      }); 

    </script> 
      <li><a id='fu' href="change_password" target="content">Change Password</a> 
      <li><a id='fu' href="delete_user" target="content">Delete User</a></li> 

我點擊和我沒有得到任何警告......

+0

可能onDomReady還沒有開通。嘗試打包在$(document).ready(function(){...}); – chovy

回答

4

的document.ready(函數() - 如果元素不在DOM在再結合沒有事件時存在處理程序將被連接到的元素。使用文檔準備函數等待DOM是準備嘗試將事件處理程序綁定到元素之前

// this is equivalent to $(document).ready(function() 
$(function(){ // <-- wait for dom ready before binding events 
$("a").click(function(e) { 
     //e.preventDefault(); //<-- not sure if you want anchor action - if not add this in 
     alert("Handler for .click() called."); 
     window.location.reload(); 
    }); 
}); 
1

的問題是執行你的JavaScript時,它指的是做元素不存在於頁面上。

您可以執行你的JavaScript的DOM準備好(你的JavaScript將等待頁面上的所有元素來執行之前加載):

<script> 
$(document).on("ready", function(){ 
    $("a").click(function() { 
     alert("Handler for .click() called."); 
     window.location.reload(); 
    }); 
}); 
</script> 

或者把你的JavaScript在頁面的末尾(所有元素將在最終運行時加載)。