在JavaScript中,我想像这样使用setTimeOut()函数
<script>
var id=12;
setTimeOut("showGrid('i want to pass variable id here')",5000);
</script>发布于 2011-12-31 13:41:10
最好的方法是将一个匿名的函数传递给setTimeout。此匿名函数将能够访问id
setTimeout(function() { showGrid(id); }, 5000);将字符串传递给setTimeout (而不是函数)通常被认为是有害的,因为字符串将是eval'd,应该避免。
还要注意,您的代码中有一个轻微的拼写错误:函数是setTimeout,而不是setTimeOut (请注意小写的o)
编辑
根据您的注释,代码将如下所示:
setTimeout(function() { document.getElementById().inerHTML = data; }, 500);当然,除了需要将某种id传递给document.getElementById之外
发布于 2017-12-12 19:34:29
如果您想使用参数,请尝试以下示例:
var x = "OK";
setTimeout(alertOK.bind(null,x), 3000);
x = "Would be WRONG";
console.log("before timeout:", x);
function alertOK(x){
console.log("after timeout:",x);
}
在循环中(创建函数是不可取的),它也是有效的。
https://stackoverflow.com/questions/8686547
复制相似问题