jquery hash reload fragment-identifier window.location

Cambia hash sin recarga en jQuery



reload fragment-identifier (4)

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''); });

Consulte aquí http://jsbin.com/edicu para obtener una demostración con un código casi idéntico

Tengo el siguiente código:

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

Esto simplemente desvanece un div en función de cuándo hace clic, pero quiero que la etiqueta hash de la URL de página cambie cuando hace clic para que la gente pueda copiarla y marcarla. 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?


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

Decidí actualizar la URL completa usando window.history.replaceState 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); } } });


Podría intentar atrapar el evento de carga. 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 probado, por lo que no puedo decir si funcionaría


Simplemente puede asignarle un nuevo valor de la siguiente manera:

window.location.hash