2009-12-21 15 views
43

tengo el siguiente código:Cambio de hash sin recarga en jQuery

$('ul.questions li a').click(function(event) { 
    $('.tab').hide(); 
    $($(this).attr('href')).fadeIn('slow'); 
    event.preventDefault(); 
    window.location.hash = $(this).attr('href'); 
}); 

Esto simplemente se desvanece un div en función de cuándo se hace clic, pero quiero la etiqueta URL de la página de hash para cambiar al hacer clic en que la gente pueda copiar y marcarlo como favorito Por el momento, esto efectivamente recarga la página cuando se cambia la etiqueta hash.

¿Es posible cambiar la etiqueta hash y no volver a cargar la página para evitar el efecto de salto?

+1

Me corrió el siguiente en esta página actual, y lo hizo exactamente lo que quiere (sin recarga de la página): $ ("a") haga clic en (function (event) {event.preventDefault(); ventana.. location.hash = $ (this) .attr ('href');}). Tal vez en el punto donde se ejecuta el código, ¿la página aún no está cargada? Compruebe cuántos elementos hay en '$ ('ul.questions li a')' –

Respuesta

70

Esto funciona para mí

$('ul.questions li a').click(function(event) { 
    event.preventDefault(); 
    $('.tab').hide(); 
    window.location.hash = this.hash; 
    $($(this).attr('href')).fadeIn('slow'); 
}); 

Marque aquí http://jsbin.com/edicu para un demo con código casi idéntica

+0

Hola, sí funciona, pero cuando la página se desplaza salta al div cuando se cambia el enlace hash. – daveredfern

+0

Verifique el código modificado que corrige eso. Si no quiere que eso suceda, solo tiene que cambiar las últimas dos líneas. La orden original era tuya y la mantuve así porque pensé que era lo que querías – jitter

+0

Gracias :) Hiciste el trabajo genial. – daveredfern

4

Puede intentar detectar el evento onload. Y detener la propagación depende de alguna bandera.

var changeHash = false; 

$('ul.questions li a').click(function(event) { 
    var $this = $(this) 
    $('.tab').hide(); //you can improve the speed of this selector. 
    $($this.attr('href')).fadeIn('slow'); 
    StopEvent(event); //notice I've changed this 
    changeHash = true; 
    window.location.hash = $this.attr('href'); 
}); 

$(window).onload(function(event){ 
    if (changeHash){ 
     changeHash = false; 
     StopEvent(event); 
    } 
} 

function StopEvent(event){ 
    event.preventDefault(); 
    event.stopPropagation(); 
    if ($.browser.msie) { 
     event.originalEvent.keyCode = 0; 
     event.originalEvent.cancelBubble = true; 
     event.originalEvent.returnValue = false; 
    } 
} 
No

a prueba, por lo que no se puede decir si funcionaría

+1

para uno, debe pasar la variable local "evento" a "StopEvent" –

+0

Vaya. Gracias editado en consecuencia. –

+0

Gracias por esto le dará un giro. – daveredfern

0

El aceptada La respuesta no funcionó porque mi página saltó ligeramente al hacer clic, arruinando mi animación de desplazamiento.

Decidí actualizar la URL completa usando window.history.replaceState en lugar de usar el método window.location.hash. Evitando así el evento hashChange activado por el navegador.

// Only fire when URL has anchor 
$('a[href*="#"]:not([href="#"])').on('click', function(event) { 

    // Prevent default anchor handling (which causes the page-jumping) 
    event.preventDefault(); 

    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 
     var target = $(this.hash); 
     target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 

     if (target.length) {  
      // Smooth scrolling to anchor 
      $('html, body').animate({ 
       scrollTop: target.offset().top 
      }, 1000); 

      // Update URL 
      window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash); 
     } 
    } 
}); 
Cuestiones relacionadas