jQuery中使用AJAX加载链接后获取href值

发布于 2024-11-29 09:16:58 字数 730 浏览 4 评论 0原文

我正在尝试使用 AJAX 更新数据库中的单个记录。一切都工作正常,但是当结果返回时,它看起来很好,但是如果再次单击 a.update (对于返回的元素),我会打开 href (所以第二次 attr() 对某些情况不起作用原因)。我对 jQuery 和 ajax 非常陌生:)

    // Update Single Item   
$('li a.update').click(function () {
updateURL = $(this).attr("href");
$(this).attr("href", "#");
theContainer = $(this).parents('li');
    $.ajax({
    type: "GET",
    dataType: 'json',
    url: updateURL,
        async: false,
    success: function(data){
        theContainer.replaceWith(data.html).fadeIn(300);
    }

    });
    return false;
    });

ps List 元素是用 PHP 生成的。当我请求单个

  • 元素时,我使用完全相同的模板生成它(默认情况下,所有内容都使用 foreach 循环打印,之后 AJAX 请求返回一个带有 <; 的 JSON)。 li>...
  • )

    I am trying to update a single record in my database with AJAX. Everything is working fine, but when the result is returned, it looks fine, but if a.update is clicked again (for the returned element) I get the href opened (so the second time the attr() doesn't work for some reason). I am very new to jQuery and ajax :)

        // Update Single Item   
    $('li a.update').click(function () {
    updateURL = $(this).attr("href");
    $(this).attr("href", "#");
    theContainer = $(this).parents('li');
        $.ajax({
        type: "GET",
        dataType: 'json',
        url: updateURL,
            async: false,
        success: function(data){
            theContainer.replaceWith(data.html).fadeIn(300);
        }
    
        });
        return false;
        });
    

    p.s. The List element is generated with PHP. When I request a single <li> element, I generate it with the exact same template (by default everything is printed with a foreach loop, afterwards AJAX requests get back a JSON with <li>...</li>)

    如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

    扫码二维码加入Web技术交流群

    发布评论

    需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

    评论(1

    可是我不能没有你 2024-12-06 09:16:58

    您可以使用 live 方法将事件侦听器附加到所有匹配的元素,无论它们是否已经在 DOM 中:

    $('li a.update').live("click", function() {
        //Your code
    });
    

    附加事件侦听器的方式只会将其附加到当前位于的元素DOM,并且当您通过 AJAX 添加新的 DOM 时,它们不会接收事件侦听器。

    You can use the live method to attach the event listener to all matching elements regardless of whether they are already in the DOM or not:

    $('li a.update').live("click", function() {
        //Your code
    });
    

    The way you are attaching the event listener will only attach it to elements currently in the DOM, and as you are adding new ones via AJAX, they don't receive the event listener.

    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文