for循环中setTimeout使用注意 客官°小女子只卖身不卖艺 2022-07-15 11:25 129阅读 0赞 **声明:本博文用于学习总结及工作心得** 使用Extjs前端框架时,需要改变框架中grid组件默认的样式;由于组件中嵌套有checkBox复选框,使用的是动态加载 所以在使用listener 监听afterrender时做动态修改组件样式,总是获取不到checkbox组件;然后改用setTimeout延迟方法的执行; 问题得以解决,但是如果该grid在当前哟多个时,通过样式选择器获取组件,得到的是一个dom数组,思路是使用for循环加setTimeout; 实际验证后确实得不到想要的结果,改变的始终是最后一个grid; 由于在setTimeout中的函数执行的时候,for循环已经完成了,获取的到checkBox组件始终是最后一个;如何让for 循环的值保留下来传递给setTimeout使用? 看下面两段代码: for(var i=0;i<10;i++){ setTimeout((function(i){ return function(){ console.log(i); } })(i),1000); } 循环的10次都是在1s后触发,所以一次性打印出来; for(var i=0;i<10;i++){ setTimeout((function(i){ return function(){ console.log(i); } })(i),(function(i){ return i*1000 })(i)); } 循环的10次每一次比前一次要延迟1s触发,所以打印效果是间隔1s。 以上两种循环方法都解决了for循环传值的问题; 业务代码: 'afterrender': function (grid) { var elements = document.querySelectorAll('.panel_title_toolbar_daily3'); for (var index = 0; index < elements.length; index++) { var nodes = elements[index].childNodes; console.info(nodes.length); if (nodes) { nodes[0].setAttribute("style", "background:url('');background-color:#fff;"); var node = nodes[1]; nodes[1].setAttribute("style", "background:url('');background-color:#fff;border:0px;"); if (node) { setTimeout((function(node){ return function(){ var childNode = node.firstChild.firstChild; var childNodes = childNode.childNodes; console.info(childNodes.length); for (var i = 0; i < childNodes.length; i++) { if (i == 0) { childNodes[i].setAttribute("style", "background:url('');background-color:#fff;border:0px;"); } childNodes[i].firstChild.setAttribute("style", "background:url('');background-color:#fff;border:0px;"); } } })(node),10); } } } }
还没有评论,来说两句吧...