【问题标题】:Cannot read property 'substring' of undefined after putting the line in setTimeout将行放入 setTimeout 后无法读取未定义的属性“子字符串”
【发布时间】:2018-02-18 20:37:16
【问题描述】:

我非常仔细地检查了浏览器中的控制台。
这一行:

document.getElementById("role_show_" + $(this).attr("id").substring(7, 9)).style.display = "block";

正常执行。但是当我像这样把它放在setTimeout 中时:

setTimeout(function() {
    document.getElementById("role_show_" + $(this).attr("id").substring(7, 9)).style.display = "block";
}, 400);

控制台显示此错误:
Uncaught TypeError: Cannot read property 'substring' of undefined

这里发生了什么?我确信所有其他代码行都未经编辑。

【问题讨论】:

    标签: jquery typeerror


    【解决方案1】:

    setTimeout 函数使您的$(this) 处于与您希望的范围不同的范围内。 要使其正常工作,请在调用 setTimeout 函数之前将 $(this) 保存到变量中。

    var that = $(this);
    setTimeout(function() {
        document.getElementById("role_show_" + $(this).attr("id").substring(7, 9)).style.display = "block";
    }, 400);
    

    所以现在您基本上可以使用thatsetTimeout 函数中访问您的$(this)

    【讨论】:

      【解决方案2】:

      这是因为$(this)。当你在函数内部时,你访问函数本身,而函数没有id 属性

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-13
        • 2016-05-28
        • 2021-03-12
        • 1970-01-01
        • 1970-01-01
        • 2020-08-30
        • 2017-11-18
        • 1970-01-01
        相关资源
        最近更新 更多