javascript 为什么可以检查 (document.addEventListener) 是否返回 false

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3907726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:39:19  来源:igfitidea点击:

why could a check if (document.addEventListener) returns false

javascriptaddeventlistener

提问by Miroo

On what basis does a check if (document.addEventListener)return false? Is there a way we can change this?

支票if (document.addEventListener)返回的依据是什么false?有什么办法可以改变这种情况吗?

回答by Nikita Rybak

if (document.addEventListener)evaluates to falseif there's no addEventListenermethod in document. This check is usually done to see if you can use this method to attach event to DOM element (works in most browsers except IE).

if (document.addEventListener)计算结果为false,如果没有addEventListener的方法document。此检查通常用于查看您是否可以使用此方法将事件附加到 DOM 元素(适用于除 IE 外的大多数浏览器)。

is there a way we can change this ?
This question I don't completely understand. Probably, you want something like document.attachEvent('onload', callback);for IE. You can't really add addEventListenermethod to document (well, maybe you can, but it wouldn't make sense).

有没有办法改变这一点?
这个问题我完全不明白。可能,你想要像document.attachEvent('onload', callback);IE这样的东西。您无法真正addEventListener向文档添加方法(好吧,也许您可​​以,但这没有意义)。

Docs for addEventListener

addEventListener 的文档

回答by Romain Linsolas

If this code snippet returns false, this means that the addEventListenermethod property is not support by the browser. This is the case for Internet Explorer, where attachEventis used instead:

如果此代码段返回false,则表示addEventListener浏览器不支持该方法属性。这是Internet Explorer的情况下,在attachEvent被代替:

if (document.addEventListener){  
  document.addEventListener(...);
} else if (document.attachEvent){  
  document.attachEvent(...);  
}

回答by Quentin

It returns a false value (although not actually false) if it isn't defined.

false如果未定义,它会返回一个假值(尽管实际上不是)。

This is a standard feature (AKA object) detectiontest.

这是一个标准特征(AKA 对象)检测测试。

You could change it by implementing your own version. More usually you'll use this in a wrapper function with the } else {having IE specific handling.

您可以通过实现自己的版本来更改它。更常见的是,您将在} else {具有 IE 特定处理的包装函数中使用它。