jQuery ajax工作一次,但此后每次都通过浏览器加载href

jQuery ajax works once, but each time thereafter loads the href through browser

本文关键字:href 加载 浏览器 工作 ajax 一次 jQuery      更新时间:2023-09-26

我有一个点击处理程序,它读取a标记的href属性并通过ajax加载新内容。该函数返回false,因此它不跟随href url。这种方法只运行一次,但此后每次都不会调用该函数,也不会异步加载内容,而是跟随浏览器中的链接。

$ ("document").ready( function () {
          $(".post_update").click( function () {
              $("#dashboard_content").html(ajax_load).load($(this).attr('href'));
              return false;
          });
});
<a href="{{ path('post_update', {"id":post.id}) }}" class="post_update">Edit</a>

你不应该使用document作为字符串,它本身就是一个对象,试试下面的代码。

由于链接在仪表板容器内,所以在这种情况下应该使用live。

$(document).ready( function () {
          $("a.post_update").live('click',  function () {
              $("#dashboard_content").html(ajax_load).load($(this).attr('href'));
              return false;
          });
});

如果.post_update#dashboard_content内部,则问题是事件处理程序绑定的元素现在已经消失了。最简单的解决方法是使用jQuery.live法。所以你的代码看起来像:

$(document).ready(function () {
    $(".post_update").live("click", function (e) {
        $("#dashboard_content").html(ajax_load).load($(this).attr('href'));
        return false;
    });
});