javascript - IOS 上的 Safari 生成 "ReferenceError: Ca ni n' t 找到变量 :"

标签 javascript ios safari

以下代码适用于所有浏览器,包括 Mac 上的 Safari,但 iPhone 上的 Safari 除外。

我有一个可能正在运行的计时器对象,其定义如下:

//delay background change until animation is finished
lastTimer = setTimeout(function () {
  $('#' + targetDiv).removeClass('open');
}, 150);

稍后,我需要检查计时器是否正在运行,如果是则取消它。这是我正在使用的代码:

if (lastTimer != null) { clearTimeout(lastTimer); }

这是 IOS Safari 生成 JavaScript 错误的地方:

"ReferenceError: Can't find variable: lastTimer".

关于为什么检查 null 不能防止错误,就像其他浏览器一样,有什么想法吗?

这是对以下回复的两个相关功能的完整代码:(使用解决方案编辑)

// Class for handling the animations for the drop down menus
var dropDownMenu = {
lastTimer: null,
openMenu: function (targetDiv) {
    if (targetDiv != null) {
        var targetHeight = $('#' + targetDiv).height();
        $('#' + targetDiv).stop(true); //stop an previous animations and clear queue
        if (this.lastTimer != null) { clearTimeout(this.lastTimer); } //stop possible pending timer to prevent background change
        console.log("testing b");
        $('#mainNavigation #dropDownMenu ul').removeClass('open'); // make sure all closed menus show corrent bgd
        $('#' + targetDiv).animate({
            bottom: -(targetHeight + 30)
        }, 200, 'swing');
        $('#' + targetDiv).addClass('open');
    }

},
closeMenu: function (targetDiv) {
    if (targetDiv != null) {
        $('#' + targetDiv).stop(true); //stop an previous animations and clear queue
        $('#' + targetDiv).animate({
            bottom: 0
        }, 200, 'swing');
        //delay background change until animation is finished
        this.lastTimer = setTimeout(function () {
            $('#' + targetDiv).removeClass('open');
        }, 150);
    }
}
}

当错误发生在 iOS 中时,执行停止并且我的测试 console.log 不会立即执行。

最佳答案

我想插话解释一下。 Mobile Safari 在使用简单检查检查 undefined 时不太宽容,

if variable

遇到这种情况就用,

if typeof variable === "undefined"

将变量附加到“this”是这里的一种解决方案,但它只是利用了 definedVariable.undefinedProperty 返回 undefined 的事实,而直接引用 undefined variable 会在某些运行时环境中导致引用错误。

如果没有必要,我建议不要养成依附于“this”的习惯。

关于javascript - IOS 上的 Safari 生成 "ReferenceError: Ca ni n' t 找到变量 :",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11021576/

相关文章:

iPhone Web 应用程序和特定输入类型

javascript - php/phpstorm toggle 自动测试在不保存文件的情况下被触发

iphone - 如何使用 Objective C 为 iOS 设备编写我自己的下载管理器

web - IOS 11 Safari 记住相机权限

iOS - 如何找到上传文件的估计剩余时间

ios - 从内存存储中删除 Core Data 对象会使它们变成错误,但不会删除它们

javascript - Safari 中的 SVG 组元素不会触发 Wheel 事件

javascript - 标签应该出现在数据表插件中文本框的右侧

javascript - 存储用户测验/测试答案的正确方法是什么?

javascript - 使用 Javascript 将 JSON 对象名称传递给函数