Javascript IE错误:'target'为null或不是对象

时间:2021-12-20 23:54:08
document.onkeydown = function(event) {
    var tagName = event.target.tagName;
    if (tagName != 'INPUT' && tagName != 'TEXTAREA' && !event.alt && event.control) {

        if (event.ctrlKey && event.keyCode == 37) {
            if (_this.currentPage > 1) {
                window.location.href = _this.baseUrl.replace(/%page%/i, _this.currentPage + 1);
            }
        } else if (event.ctrlKey && event.keyCode == 39) {
            if (_this.currentPage < _this.pagesTotal) {
                window.location.href = _this.baseUrl.replace(/%page%/i, _this.currentPage - 1);
            }
        }
    }
}

This gives me an error only in IE 8:

这只在IE 8中出现错误:

'target' is null or not an object

'target'为null或不是对象

for that line var tagName = event.target.tagName;

对于该行var tagName = event.target.tagName;

How to fix that. Error happens when I press Ctrl or arrows button.

如何解决这个问题。按Ctrl或箭头按钮时发生错误。

2 个解决方案

#1


3  

Do it like this:

像这样做:

event = event || window.event;
var tagName = (event.target || event.srcElement).tagName.toUpperCase();

#2


5  

IE does not pass in the event object into the event handler. Instead, they use the global event property of the window object. So for IE, you'd use window.event instead.

IE不会将事件对象传递到事件处理程序中。相反,它们使用窗口对象的全局事件属性。所以对于IE,你会使用window.event。

It is common practice to test for the supplied argument first. You also have to take into account the fact the IE uses srcElement instead of target. To account for all that, use something similar to this:

通常的做法是首先测试提供的参数。您还必须考虑IE使用srcElement而不是target的事实。为了解释这一切,请使用与此类似的内容:

document.onkeydown = function(event) {
    event = event || window.event;
    var tagName = (event.target || event.srcElement).tagName;
    // Keep up the good work...
}

This should do the trick.

这应该可以解决问题。

#1


3  

Do it like this:

像这样做:

event = event || window.event;
var tagName = (event.target || event.srcElement).tagName.toUpperCase();

#2


5  

IE does not pass in the event object into the event handler. Instead, they use the global event property of the window object. So for IE, you'd use window.event instead.

IE不会将事件对象传递到事件处理程序中。相反,它们使用窗口对象的全局事件属性。所以对于IE,你会使用window.event。

It is common practice to test for the supplied argument first. You also have to take into account the fact the IE uses srcElement instead of target. To account for all that, use something similar to this:

通常的做法是首先测试提供的参数。您还必须考虑IE使用srcElement而不是target的事实。为了解释这一切,请使用与此类似的内容:

document.onkeydown = function(event) {
    event = event || window.event;
    var tagName = (event.target || event.srcElement).tagName;
    // Keep up the good work...
}

This should do the trick.

这应该可以解决问题。