0

我在这里想念什么?

<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>

我点击并没有收到警报......

4

2 回答 2

4

document.ready(function() - 如果在绑定时元素在 dom 中不存在,则不会将事件处理程序附加到元素。使用 document ready 函数等待 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();
  });
});
于 2012-09-20T19:53:41.603 回答
1

问题是当你的 JavaScript 被执行时,它引用了页面上还不存在的元素。

您可以在 DOM 准备好时执行 JavaScript(您的 JavaScript 将等待页面上的所有元素在执行之前加载):

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

或者将您的 JavaScript 放在页面末尾(所有元素将在最终运行时加载)。

于 2012-09-20T19:56:25.020 回答