2013-02-28 130 views
0

我使用的jQuery maximage其核心jQuery Cycle瀏覽幻燈片,並修改(替換)每個過渡位置哈希。快速location.replace導致瀏覽器崩潰

它的作品,除非你嘗試和導航得太快;此時瀏覽器(在Firefox和Chrome中測試)會崩潰,因爲頁面會無休止地嘗試重新加載自身。

$(function(){ 
    var h, 
     hash = window.location.hash, 
     hashes = {}, 
     index = 0; 
    // Iterate slides into hashes object 
    $('#slides').children('div').each(function(i) { 
     h = $(this).attr('id'); 
     // Change IDs to hash format 
     h = h.replace(/\ /g, '-'); 
     hashes[h] = i; 
     slideInteger = i 
    }); 
    if (hash) { 
     index = hashes[hash.substring(1)] || index; 
    }; 
    $('#slides').maximage({ 
     cycleOptions: { 
      startingSlide: index, 
      cssTransitions: true, 
      after: onAfter, 
      fx: 'fade', 
      speed: 360, 
      timeout: 0 
     }, 
     onFirstImageLoaded: function(){ 
      $('#cycle-loader').hide(); 
      // Remove tooltip on hover 
      $('.mc-image').hover(function(){ 
       $(this).removeAttr('title'); 
      }); 
     } 
    }); 
    function onAfter(el, next_el, opts) { 
     var nextHash = $(next_el).find('.slideLink').text().toLowerCase().replace(/\ /g, '-'); 
     window.location.replace(('' + window.location).split('#')[0] + '#' + nextHash); 
    }; 
    $(window).on("hashchange", function() { 
     $('#slides').cycle(hashes[window.location.hash.substring(1)] || 0); 
    }); 
}); 

我試着用...

function onAfter(el, next_el, opts) { 
    var nextHash = $(next_el).find('.slideLink').text().toLowerCase().replace(/\ /g, '-'); 
    if(window.location.hash != ('#' + nextHash)){ 
     window.location.replace(('' + window.location).split('#')[0] + '#' + nextHash); 
    } 
}; 

更換onAfter功能...但它似乎沒有任何區別。

這似乎並不是我可以在jsfiddle中複製的任何東西 - 因此缺乏物理演示的道歉。

+1

小心閱讀'window.location.hash'。從歷史上看,一些瀏覽器會返回一個帶'#'前導字符串的字符串,而另一些瀏覽器則沒有(IIRC,該標準說它應該沒有)。雖然所有主流瀏覽器現在都可以符合,但允許'window.location.hash'返回任一版本仍然是明智之舉。 – 2013-02-28 12:09:36

+0

我不知道 - 謝謝。 – verism 2013-02-28 12:23:57

回答

1

您應該使用HTML5 history.pushState/history.replaceState API。您也可以使用舊版瀏覽器的墊片。

https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history 「添加和修改歷史項」

+0

我猜你的意思是history.replaceState - 因爲我不想添加任何其他歷史條目。但是,這工作,謝謝。現在支持舊瀏覽器的問題... – verism 2013-02-28 12:18:42

+0

這是一個墊片:https://github.com/balupton/history.js – Ven 2013-02-28 12:32:13