jquery - 将行放入 setTimeout 后无法读取未定义的属性 'substring'

标签 jquery typeerror

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

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);

控制台显示此错误:
未捕获类型错误:无法读取未定义的属性“子字符串”

这是怎么回事?我确信所有其他代码行都未经编辑。

最佳答案

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

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

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

关于jquery - 将行放入 setTimeout 后无法读取未定义的属性 'substring',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46141535/

相关文章:

php - 使用 Jquery/Javascript/Ajax 和 PHP/Mysql 进行分页

python - 类型错误:强制转换为 Unicode:需要字符串或缓冲区,找到类型

python - 为什么会出现 TypeError : 'int' object is not subscriptable using for loop and not with list-comprehension in python

从按钮到函数的 JavaScript 事件

jQuery 进度条值未设置

jquery - 确定 HTML/DOM 中哪个元素排在第一位?

javascript - JScrollPane 不会滚动整个 div? -- JScrollPane 不会随 div 在窗口调整大小时动态移动

python - 类型错误:button_click() 缺少 1 个必需的位置参数: 'self'

javascript - 未捕获的类型错误 : Object [object Object] has no method 'slides'

Python 不可订阅