我非常仔细地检查了浏览器中的控制台。
这一行:
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/