Изменить содержимое div и URL-адрес хеша

0

Я создал полностью функциональный скрипт замены содержимого Ajax. Проблема заключается в том, что он добавляет вперед, например, /# about или /# work или /# contact к адресу, но когда я перезагружаю сайт, главная страница будет показана. Зачем? Как возможно, что, когда я наберу адрес, будет отображаться правая подстраница?

Кто-то сказал мне, что проблема в том, что я добавил файл вручную, когда использую popstate. Поэтому я хочу решение без popstate. Я не эксперт Javascript, но я хотел бы изучить его. Потому что popstate, но это очень круто.

window.location.hash = $(this).attr('href'); 

Мои.html файлы хранятся в /data/. Странно то, что он находит файл, но когда я пытаюсь найти его вручную, страница показывает главную страницу или когда я обновляю сайт с помощью F5, также будет показана главная страница.

Можете ли вы мне помочь и показать, как это работает. Мы можем использовать мой код, чтобы найти ошибку. Большое спасибо.

Вот ссылка Websitelink: Demo Link

function refreshContent() {
var targetPage = 'home';
var hashMatch = /^#(.+)/.exec(location.hash);
// if a target page is provided in the location hash
if (hashMatch) {
  targetPage = hashMatch[1];
}
$('#allcontent').load('data/' + targetPage + '.html');
}


$(document).ready(function(){
refreshContent();
window.addEventListener('hashchange', refreshContent, false);
$('.hovers').click(function() {
var page = $(this).attr('href'); 
$('#allcontent').fadeOut('slow', function() {
$(this).animate({ scrollTop: 0 }, 0);
$(this).hide().load('data/' + page +'.html').fadeIn('normal');
});

});
});

$('.hovers').click(function() {
  window.location.hash = $(this).attr('href'); 
  $.get('data/'+this.href, function(data) {
    $('#allcontent').slideTo(data)      
  })
  return false  
})
  • 0
    Кажется, здесь работает. Перезагрузка ничего не меняет в URL.
  • 0
    Может быть, это может быть полезно: stackoverflow.com/questions/680785/…
Теги:

1 ответ

2
Лучший ответ

Вы должны загрузить начальную страницу на основе location.hash (если предусмотрено) при загрузке страницы:

function refreshContent() {
   var targetPage = 'home';
   var hashMatch = /^#!\/(.+)/.exec(location.hash);
   // if a target page is provided in the location hash
   if (hashMatch) {
      targetPage = hashMatch[1];
   }
   $('#allcontent').load('data/' + targetPage + '.html');
}


$(document).ready(function(){
   refreshContent();
   ...

Вы можете сделать назад и вперед работу, прослушивая событие Window.onhashchange:

window.addEventListener('hashchange', refreshContent, false);

Обратите внимание, что это не работает в Internet Explore 7 или ниже.

Редактировать:

Хорошо, попробуйте следующее:

var $contentLinks = null;
var contentLoaded = false;

function refreshContent() {
   var targetPage = 'home';
   var hashMatch = /^#(.+)/.exec(location.hash);
   var $content = $('#allcontent');

   // if a target page is provided in the location hash
   if (hashMatch) {
      targetPage = hashMatch[1];
   }

   // remove currently active links
   $contentLinks.find('.active').removeClass('active');
   // find new active link
   var $activeLink = $contentLinks.siblings('[href="' + targetPage + '"]').find('.navpoint');
   // add active class to active link
   $activeLink.addClass('active');
   // update document title based on the text of the new active link
   window.document.title = $activeLink.length ? $activeLink.text() + ' | Celebrate You' : 'Celebrate You';

   // only perform animations are the content has loaded
   if (contentLoaded) {
       $content
           .fadeOut('slow')
           .animate({ scrollTop: 0 }, 0)
       ;
   }

   // after the content animations are done, load the content
   $content.queue(function() {
       $content.load('data/' + targetPage + '.html', function() {
           $content.dequeue();
       });
   });

   if (contentLoaded) {
       $content.fadeIn();
   }

   contentLoaded = true;
}

$(document).ready(function() {
    $contentLinks = $('.hovers');

    refreshContent();

    window.addEventListener('hashchange', refreshContent, false);

    $contentLinks.click(function(e) {
        e.preventDefault();
        window.location.hash = '!/' + $(this).attr('href'); 
    });
});
  • 0
    Я обновил ответ.
  • 0
    Мой плохой, $(window).hashchange не существует, потому что он поддерживается не во всех браузерах. Я обновил код для window.addEventListener('hashchange', refreshContent, false); ,
Показать ещё 21 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню