开发者

Return link for another (same) XMLHttpRequest

开发者 https://www.devze.com 2023-01-23 01:43 出处:网络
I have one link that makes an ajax request and it prints by XHR request another link same at this one before cliked

I have one link that makes an ajax request and it prints by XHR request another link same at this one before cliked

so it's like a lo开发者_开发百科op:

starting XHR from

<a href="javascript:void(0)" class="doXHR">do XHR</a>

than into Ajax success function i repeat into my html this link:

<a href="javascript:void(0)" class="doXHR">do XHR</a>

but when i output the same link to html by success function of previous doHXR call it doesn't allow me to do another(doXHR ajax call)

so if i click on same link,but same link is generated from ajax,it doesn't allow me to send another(same) doXHR request... :/

any idea?

sorry for my bad english :P


It seems to me that you assign an event listener to your do XHR link and it looks like the callback function is changing that link with the code you mentioned.

When doing so, the original event listener attached to that link is gone and you'll have to reattach it. Another possibility is to use jQuery's .live function, which also fires events on elements attached to the DOM after 'binding' the event listener:

$(".doXHR").live('click', function() {
  // Live handler called.
});


I wouldn't remove the link and then entirely recreate it when you do the Ajax request. And if you are just using XMLHttpRequest directly, I recommend that you look at the wonderful jQuery Ajax documentation for how to do it in the jQuery way.

Doing it the right way

If you need to prevent a second successive click on the link from having any effect (until the request has completed, that is), you can use jQuery's .one() method to ensure that the event handler fires only once:

$(function() {
    function doAjax() {
        $.ajax({..., success: function() {
            // Do what you must to the HTML page

            // Allow the user to click again to make the request again
            $('.doXHR').one('click', doAjax);
        }, ...});
    }

    $('.doXHR').one('click', doAjax);
});

Hiding or changing the color of the link

If you want the page to act as if the link is removed while the request takes place:

$('.doXHR').css('display', 'none'); // before Ajax request
$('.doXHR').css('display', ''); // after Ajax request

If you just want to gray out the link, use:

$('.doXHR').css('color', 'gray'); // before Ajax request
$('.doXHR').css('color', ''); // after Ajax request

This is in addition to using .one(...) to bind the click event handler.

0

精彩评论

暂无评论...
验证码 换一张
取 消