当前位置: 动力学知识库 > 问答 > 编程问答 >

jQuery loads page twice but why?

问题描述:

I have an navigation where i load a page into a div called target. It works well but with a slightly annoying bug.

When I press a nav link it hides the current content and load the new one but then it hides the new one and show it again. In firebug i see that the script makes two requests for the page it's trying to load. But i cant understand why it loads it twice?

Heres my jquery:

$(".nav").click(function(e){

e.preventDefault();

$(".footer").hide(0);

$('#target').html('<div class="content">Loding...</div>');

$.get(this.href, function(data) {

$("#target").hide(0, function(){

$("#sub_menu").fadeOut("fast");

$(".footer").show(0);

$(this).html(data).show(0);

});

});

});

Best regards!

网友答案:

This is from my comment on the OP:

Make sure your code for the click only loads ONCE.

网友答案:

My guess will be that you got 2 elements with class "nav".

Try alert($(".nav").length); to check how many elemnts you got.

网友答案:

The chances are your event is bubbling up from the actual event target and the handler is bound to an ancestor, in which case it will fire twice.

You can stop that from happening by calling the stopPropagation method of the event object:

$(".nav").click(function(e) {
    e.stopPropagation();
    //etc...
});
网友答案:

There are several reasons why this might be happening, but there are a few different things that you could do to prevent it in the first place. First, make sure that you're not reapplying the handlers when content is loaded via AJAX. Any scripts in content fetched via AJAX should only apply to the content being loaded. Second, if you suspect that you may be reapplying handlers or need to replace an existing handler, remove the handlers for the event before applying the new one. Third, when you know that the handler being invoked should be the only one running on the element stop propagation AND prevent the default action if appropriate. The easiest way to do this is to return false from your handler.

 $('.nav').unbind('click').click( function() {
     ...
     return false;
 });
分享给朋友:
您可能感兴趣的文章:
随机阅读: