简体   繁体   English

获取hashchange事件以适用于所有浏览器(包括IE7)

[英]Get the hashchange event to work in all browsers (including IE7)

I have some code (written by another developer) that is doing AJAX page loading inside of WordPress (eg no page reloads) when you click a nav item, AJAX refreshes the primary content area. 我有一些代码(由另一个开发人员编写)在WordPress内部进行AJAX页面加载(例如,没有页面重新加载),当您单击导航项时,AJAX刷新主要内容区域。 My problem is that it's broken in IE7 and I have no idea where to start in terms of debugging. 我的问题是它在IE7中被破坏了,我不知道从哪里开始调试。

The original opening lines were 原来的开场线是

var queue = 0;

$('document').ready(function() {
    window.addEventListener("hashchange", hashChange, false);

    // Define window location variables
    var windowHost = window.location.host,
        windowHash = window.location.hash,
        windowPath = window.location.pathname;

But I changed them to make the addEventListener conditional on the basis of whether that method was present or not. 但我改变它们以使addEventListener条件,因为该方法是否存在。 Some research told me that the method is not available in older versions of IE (eg 7 in my case). 一些研究告诉我,该方法在旧版本的IE中不可用(例如在我的情况下为7)。 Also, the IE7 debug console was identifying that as an unavailable method, so that's pretty clear. 此外,IE7调试控制台将其识别为不可用的方法,因此非常清楚。 I rewrote the lines as follows, but the code is still not working: 我重写了以下行,但代码仍然无法正常工作:

var queue = 0;

$('document').ready(function() {
    if(window.addEventListener) {
        window.addEventListener("hashchange", hashChange, false);
    }
    else if (window.attachEvent) {
        window.attachEvent("hashchange", hashchange, false);    
    }
    // Define window location variables
    var windowHost = window.location.host,
        windowHash = window.location.hash,
        windowPath = window.location.pathname;

The full original script can be viewed in this pastebin: http://pastebin.com/Jc9ySvrb 可以在此pastebin中查看完整的原始脚本: http//pastebin.com/Jc9ySvrb

  • attachEvent requires events to be prefixed with on . attachEvent要求事件以on为前缀。
  • You've different capitalizations for the method. 您对该方法有不同的大小写。 Change hashchange in attachEvent to hashChange to get the event to work in IE8. 更改hashchangeattachEventhashChange获得在IE8工作的事件。
  • Use the suggested implementation to support the hashchange implementation for IE7- and other old browsers. 使用建议的实现来支持IE7和其他旧浏览器的hashchange实现。

I have created a cross-browser implementation, which adds the hashchange feature to browsers, even those who do not support it. 我创建了一个跨浏览器实现,它将hashchange功能添加到浏览器,甚至是那些不支持它的人。 The fallback is based on the specification . 后备基于规范

//function hashchange  is assumed to exist. This function will fire on hashchange
if (!('onhashchange' in window)) {
    var oldHref = location.href;
    setInterval(function() {
        var newHref = location.href;
        if (oldHref !== newHref) {
            var _oldHref = oldHref;
            oldHref = newHref;
            hashChange.call(window, {
                'type': 'hashchange',
                'newURL': newHref,
                'oldURL': _oldHref
            });
        }
    }, 100);
} else if (window.addEventListener) {
    window.addEventListener("hashchange", hashChange, false);
}
else if (window.attachEvent) {
    window.attachEvent("onhashchange", hashChange);    
}

Note: This code is useful for one hashchange event . 注意:此代码对一个hashchange事件很有用。 If you want to add multiple hashchange handlers , use the following method. 如果要添加多个hashchange处理程序 ,请使用以下方法。
It defines two functions, addHashChange and removeHashChange . 它定义了两个函数, addHashChangeremoveHashChange Both methods take a function as an argument. 两种方法都将函数作为参数。

(function() {
    if ('onhashchange' in window) {
        if (window.addEventListener) {
            window.addHashChange = function(func, before) {
                window.addEventListener('hashchange', func, before);
            };
            window.removeHashChange = function(func) {
                window.removeEventListener('hashchange', func);
            };
            return;
        } else if (window.attachEvent) {
            window.addHashChange = function(func) {
                window.attachEvent('onhashchange', func);
            };
            window.removeHashChange = function(func) {
                window.detachEvent('onhashchange', func);
            };
            return;
        }
    }
    var hashChangeFuncs = [];
    var oldHref = location.href;
    window.addHashChange = function(func, before) {
        if (typeof func === 'function')
            hashChangeFuncs[before?'unshift':'push'](func);
    };
    window.removeHashChange = function(func) {
        for (var i=hashChangeFuncs.length-1; i>=0; i--)
            if (hashChangeFuncs[i] === func)
                hashChangeFuncs.splice(i, 1);
    };
    setInterval(function() {
        var newHref = location.href;
        if (oldHref !== newHref) {
            var _oldHref = oldHref;
            oldHref = newHref;
            for (var i=0; i<hashChangeFuncs.length; i++) {
                hashChangeFuncs[i].call(window, {
                    'type': 'hashchange',
                    'newURL': newHref,
                    'oldURL': _oldHref
                });
            }
        }
    }, 100);
})();
// Usage, infinitely many times:
addHashChange(function(e){alert(e.newURL||location.href);});

attachEvent takes on two params: attachEvent有两个参数:

bSuccess = object.attachEvent(sEvent, fpNotify)

[And is needed for all versions of IE below IE9! [并且IE9以下的所有IE版本都需要! :( See MDN reference ] :(见MDN参考

This could work: 这可能有效:

if(window.addEventListener) {
    window.addEventListener("hashchange", hashChange, false);
}
else if (window.attachEvent) {
    window.attachEvent("onhashchange", hashchange);//SEE HERE...
    //missed the on. Fixed thanks to @Robs answer.
}

Of course if it is possible, you should just use JQuery, since it encapsulates all this for your. 当然,如果有可能,你应该只使用JQuery,因为它封装了所有这些为你的。

And as always there is a plugin out there: http://benalman.com/projects/jquery-hashchange-plugin/ 和往常一样有一个插件: http//benalman.com/projects/jquery-hashchange-plugin/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM