javascript IE8 JS 错误:对象不支持此属性或方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24069619/
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
IE8 JS error: Object doesn't support this property or method
提问by IEcansuckit
I'm using the following JS I found online to implement a responsive navigation. There is nothing on the source about having any errors in IE8, however I'm doing some compatibility testing in BrowserStack (Win7+IE8) and getting the "Object doesn't support this property or method" error. Here is the entire script:
我正在使用我在网上找到的以下 JS 来实现响应式导航。源代码中没有关于 IE8 中出现任何错误的任何内容,但是我正在 BrowserStack (Win7+IE8) 中进行一些兼容性测试并得到“对象不支持此属性或方法”错误。这是整个脚本:
<script>
$(function() {
var pull = $('#menu');
menu = $('nav ul');
menuHeight = menu.height();
$(pull).on('click', function(e) {
e.preventDefault();
menu.slideToggle();
});
});
$(window).resize(function(){
var w = $(window).width();
if(w > 320 && menu.is(':hidden')) {
menu.removeAttr('style');
}
});
</script>
And this is the line that IE8 doesn't like (character 6 specifically):
这是 IE8 不喜欢的行(特别是字符 6):
if(w > 320 && menu.is(':hidden')) {
Any help in solving this would be awesome, I'm still not the best at JS.
解决这个问题的任何帮助都会很棒,我仍然不是 JS 中的佼佼者。
采纳答案by jfriend00
Just stop storing jQuery objects in globals at all. It doesn't cost much to just create them upon demand and you don't get into this lifetime/scoping issue that you had:
完全停止在全局变量中存储 jQuery 对象。按需创建它们不会花费太多,而且您不会遇到这个生命周期/范围界定问题:
<script>
$(function() {
$('#menu').on('click', function(e) {
e.preventDefault();
$('nav ul').slideToggle();
});
});
$(window).resize(function(){
var menu = $('nav ul');
if($(window).width() > 320 && menu.is(':hidden')) {
menu.removeAttr('style');
}
});
</script>
Some general design/code layout thoughts that apply here:
一些适用于此处的通用设计/代码布局思想:
- Avoid globals whenever possible.
- Don't declare something in one scope and then try to use it in another scope (won't work unless global so see rule #1) and if global may have timing issues too.
- Fetch selector results only when needed in the function where they are consumed. There is very, very rarely a reason to cache something like that beyond the lifetime of a function.
- If you are going to refer to the same jQuery object more than once within a function, then you may want to save it into a local variable for the duration of the function (as long as its results won't be modified within the function).
- 尽可能避免全局变量。
- 不要在一个范围内声明一些东西,然后尝试在另一个范围内使用它(除非全局,否则不会工作,所以请参阅规则#1),如果全局也可能有时间问题。
- 仅在使用它们的函数中需要时才获取选择器结果。很少有理由在函数的生命周期之外缓存类似的东西。
- 如果您要在一个函数中多次引用同一个 jQuery 对象,那么您可能希望在函数运行期间将其保存到一个局部变量中(只要它的结果不会在函数内被修改) .
回答by Chris
I hope you realize that single var statement doesn't apply to all of the variables. You are declaring global variables.
我希望您意识到单个 var 语句不适用于所有变量。您正在声明全局变量。