简体   繁体   English

在 jQuery 中加载带有 AJAX 的链接后获取 href 值

[英]Get href value after loading the link with AJAX in jQuery

I am trying to update a single record in my database with AJAX.我正在尝试使用 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).一切正常,但是当返回结果时,它看起来很好,但是如果再次单击 a.update(对于返回的元素)我打开了 href(所以第二次 attr() 对某些人不起作用原因)。 I am very new to jQuery and ajax:)我对 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 The List element is generated with PHP. ps List 元素是使用 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> )当我请求单个<li>元素时,我使用完全相同的模板生成它(默认情况下,所有内容都使用 foreach 循环打印,然后 AJAX 请求返回一个带有<li>...</li>的 JSON )

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

$('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.您附加事件侦听器的方式只会将其附加到当前在 DOM 中的元素,并且当您通过 AJAX 添加新元素时,它们不会收到事件侦听器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM