2010-11-12 13 views
5

Tengo un enlace que tiene un href de "/news#1930". Cuando hago clic en este enlace cuando está en la página /news, no actualiza la página (solo agrega # 1930 al final de la URL). Sin embargo, me gustaría actualizar la página (estoy usando la información después de la etiqueta # con algunos jquery para cargar ese artículo específico en un iframe correspondiente y cuando no se actualiza no cargará el nuevo artículo). ¿Alguna idea sobre cómo forzar la actualización?Cómo hacer que la página con Hash Tag Href Refresh

El código que tengo actualmente es:

$(document).ready(function() { 
    var $news_story  = $(window.location.hash.substring(1)), 
     $news_number  = $news_story.selector, 
     $news_url   = 'http://www.synergy-pr.com/news/mediacenter/index.html?view=article&CustomerID=41b1if9-a17d4va5sf7of15e3kb0pa3kd2y-99d03n8sq4ad2xk8h47j00r98el5pf&ClientArticleID=' + $news_number, //url of specific article 
     $news_url_default = 'http://www.synergy-pr.com/news/mediacenter/index.html?CustomerID=41b1if9-a1hd4xa52f78f1ke3bb0oa3ld2k-90208c8g64x02nh8wf7ad0m181p5su'; //url of general news page 

     if ($news_number.length>0) { //if their is a # with a number, this means it is a sidebar link and should load that specific article 
      $('#news-feed').attr('src', $news_url); 
     } else { //if not, load the main news page 
      $('#news-feed').attr('src', $news_url_default); 
     } 
}); 

Respuesta

-5

Pruebe un espacio antes de la almohadilla:

"/news #1930" 
+0

bien buena llamada,. Eso funciona para el único enlace, pero en realidad tengo tres de estos enlaces. Cuando todos tienen espacios, ocurre el mismo problema de no actualizar. Lo pirateé al poner un espacio entre el primero, dos entre el segundo y tres entre el tercero. Esto funciona, pero no puede ser la mejor manera de hacerlo. ¿Alguna idea sobre cómo mejorar esto? – Andrew

+0

No hay mucho para hash URLs. No creo que haya otra ruta. Tal vez tokenizar el valor de hash sería un buen sustituto para usar múltiples. –

6

hashes tienen el propósito de no causar una recarga de la página. Si está utilizando jQuery para cargar ese artículo, es posible que desee ejecutar history.go (0) o window.location.reload, luego use jQuery para encontrar la etiqueta hash y el proceso (en el evento de carga de la página actualizada).

$(document).ready(function(){ 
    loadArticle = function(articleId){ 
    // code to query/load the article 
    }; 
    if (window.location.hash) 
    articleLoad(window.location.hash); 

    $('.articleLink').click(function(){ 
    window.location.hash = $(this).attr('rel'); 
    window.location.reload(); 
    }); 
}); 

EDITAR supongo que vas hash de la ruta por la misma razón sitios web como facebook hacerlo así - para la capacidad libro-marca y la indexación a pesar de estar usando ajax para la integración sin fisuras.

EDIT 2 Esto es lo que se me ocurrió para mostrar a qué me refiero. Esto cargará un hash que se ha pasado a través de la URL y manejará todos los clics nuevos a los nuevos artículos dentro de la página.

<html> 
    <head> 
    <title>Article Viewer</title> 

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script> 
    <script type="text/javascript"> 
     $(document).ready(function(){ 

     // loader function to serve up the correct article (pushes the article number to an iFrame 
     // so it can remotely load the article within the page 
     loadArticle = function(articleId){ 
      // set the hash (incase it's called from a link instead of a page load) 
      window.location.hash = articleId; 
      // change the iFrame src to the actual path fo the article page (customize this to fit your needs) 
      $('#article-frame').attr('src','view_article.php?article='+articleId); 
     }; 

     // check for a hash (#????) tag in the URL and load it (to allow for bookmarking) 
     if (window.location.hash) 
      loadArticle(window.location.hash.substring(1)); 

     // attack a click event to all the links that are related to loading an article 
     $('.article-link').click(function(){ 
      // grab raw article id from rel tag 
      var articleId = $(this).attr('rel'); 

      // shove loading it off to the "loader" 
      loadArticle(articleId); 

      // cancel the navigation of the link 
      return false; 
     }); 
     }); 
    </script> 
    </head> 

    <body> 
    <ul> 
     <?php for ($a = 1; $a < 10; $a++) echo "<li><a href=\"view_article.php?article={$a}\" rel=\"{$a}\" class=\"article-link\">View Article {$a}</a></li>\r\n  "; ?> 
    </ul> 
    <iframe id="article-frame" src="view_article.php?article=0" width="640" height="480"> 
     This page uses frames, unfortunately your browser does not support them. 
    </iframe> 
    </body> 
</html> 
+0

El artículo está ubicado dentro de un iframe, que es realmente lo que causó todos estos problemas. En todas las páginas del sitio, tiene vínculos a la barra lateral para artículos dentro del iframe. Necesitaba una forma de enlazar a la página de noticias y luego abrir el artículo correcto. La forma en que encontré esto fue agregar una etiqueta hash a los enlaces de la barra lateral, luego convertir eso a un número de cuatro dígitos correspondiente a la ID de artículos y anexarlo al final de la URL iframe. Funciona en todas las páginas a excepción del problema anterior. Si tiene un mejor enfoque para todo el problema, estaría abierto a ello con seguridad. – Andrew

+0

En la función loadArticle() anterior, puede informar al iFrame para cambiar de ubicación (algo con el efecto de $ ('#iframe') .attr ('src', 'http: //mysite.com/article'+articleId+' .html '); - A menos que no entienda completamente la situación, lo que está tratando de lograr debería ser bastante simple. –

+0

Estoy seguro de que esto debería ser bastante fácil, pero estoy teniendo algunos problemas para resolverlo. He agregado el código que tengo actualmente en mi pregunta anterior. Esto (con la cantidad diferente de espacios entre cada etiqueta de enlace #) funciona muy bien, solo sé que esta no es la mejor manera de hacerlo y me gustaría hacerlo de la manera correcta camino. Cualquier ayuda sería increíble. – Andrew

-1

Prueba esto:

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

    var location = $(window).attr('location').pathname.substring(1); 
    var goingToPage = $(this).attr('href'); 

    // if goingToPage is same page as current page, then assign new url and reload 
    // this is required to reload the page on a hash tag 
    if(goingToPage.indexOf(location) != -1){ 
     $(window).attr('location').assign(goingToPage); 
     $(window).attr("location").reload(); 
    } 
}); 
}); 
0

$("a").click(function() { 
 
     var hash = this.hash; 
 
     if (hash != "" || hash!= null) 
 
      window.location.reload(); 
 
    });

Este código se vuelve a cargar cada vínculo tiene bruja de hash

Cuestiones relacionadas