我对history.js有问题,我不知道该如何解决。
在我正在开发的网站上,我们使用history.js在页面之间移动--如果您单击history.js通过AJAX加载URL的任何链接,更新URL并为内容创建转换效果。但是,我们也有带有项的索引页面;如果单击某个项,则history.js 不是使用的--内容通过ajax加载并显示在弹出窗口中。还有一种情况是,用户可以打开条目的URL (例如,在新选项卡中,或者从搜索中),在这种情况下,用户应该被重定向到带有条目URL哈希的索引页面,这将告诉JS运行单击具有散列URL的链接的事件。但是,history.js启动并重定向到item URL。
重申:
我使用的是HTML5版本的history.js (我认为它的行为不应该是这样的,但不知道),它在加载history.js后立即重定向(页面上没有其他脚本)。除了将重定向更改为/items/?/item-id/之外,还有其他方法来解决这个问题(我认为)应该解决这个问题。
为说明这一问题:
a.html
<html>
<body>
<script type='text/javascript' src="native.history.js"></script>
<a href="b.html#/b/">b</a>
</body>
</html>b.html
<html>
<body>
<script type='text/javascript' src="native.history.js"></script>
<a href="a.html#/a/">a</a>
</body>
</html>使用native.history.js,它是history.js的纯HTML5版本,没有任何框架绑定:https://github.com/browserstate/history.js/blob/master/scripts/bundled-uncompressed/html5/native.history.js
它说明了这一点,没有任何重定向。只要单击任何链接,history.js就会在散列后重定向到URL。
发布于 2014-07-25 18:31:37
我决定直接修改history.js并添加一个选项preventHashRedirect
-
#1820 // if (currentState ) {
+
#1820 // if (!History.options.preventHashRedirect && currentState ) {解决了这个问题。(基本上,哈希更改不被视为流行状态,也不触发状态更改)。
可能更改isTraditionalAnchor函数(确定什么被认为是锚点,以及#之后的URL )来处理以!开头的所有散列将是一个更好的主意。
-
#1052 // var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
+
#1052 // var isTraditional = /^!/.test(url_or_hash) ? true : !/[\/\?\.]/.test(url_or_hash);通过这种方式,您实际上可以防止history.js影响从!开始的任何重定向。(例如,如果您实际上有一个名为my.puppy的锚,那么执行<a href='#!my.puppy'>不会导致通过history.js重定向。
下面关于@Martin Barker的想法仍然有效,尽管添加额外的重定向让我觉得有点.粗俗。
发布于 2014-07-25 12:07:12
删除--因为您不能使用History.js,所以您想怎样使用它,因为您将在系统中更改一个核心函数,这会导致无法描述的问题。
你在使用jQuery时自己做的更好--这很简单
a.html
<a href="b.html" class="hashlink">B</a>b.html
<a href="a.html" class="hashlink">A</a>这将在窗口上提供HTML5 .onhashchange事件。
// support onhashchange for browsers without support
(function(w, l, u){
'use strict';
if(w.onhashchange == u ){
w.onhashchange = function(curr, old){};
w.oldHash = l.hash.replace("#", "");;
w.onhashchangeCheck = function(){
var hash = l.hash.replace("#", "");
if(hash != w.oldHash){
w.onhashchange(hash, w.oldHash);
w.oldHash = hash;
}
}
setInterval(w.onhashchangeCheck, 100);
}
})(window, document.location);这展示了如何使用onhashchange,以及如何使用类hashlink设置任何hashlink标记来更改哈希,而不是重定向浏览器。
// handle using hash changes
(function($, w, l, d, u){
'use strict';
w.onhashchange = function(new, old){
// this should handle loading your content via ajax
// on $.ajax().success should handle reading the file into the
// content area of your sight
alert("hash has said you want to load '"+new+"'");
}
$(d).ready(function(){
$('a.hashlink').on('click', function(e){
l.hash = $(this).attr('href');
e.preventDefualt(); // jQuery stop the a link default behavioured of redirecting
//return false; // legacy jQuery support if you need it for the above
});
});
})(jQuery, window, document.location, document);请注意,在javascript中有一个u在closer函数中,但是我没有将参数输入到该变量的函数中,而是有意创建一个真正的undefined结果,如果您的代码中有些代码有var undefined = 'something it should not'
https://stackoverflow.com/questions/24757216
复制相似问题