简体   繁体   English

如何使此函数与javascript循环?

[英]How can I make this function loop with javascript?

function argsToArray(args) {
  var r = []; for (var i = 0; i < args.length; i++)
    r.push(args[i]);
  return r;
}

argsToArray(document.getElementsByTagName('img')).forEach(function(img) {
  img.src = img.src.split('VTlibOlte8YCb').join('X0X810D0' + Math.floor((Math.random()*10)+1));;
});

I tried adding setInterval(argsToArray,500); 我尝试添加setInterval(argsToArray,500); at the end but that seem to have broken things. 最后,但这似乎是坏事。

This is quite archaic and will probably crash the browser, but for this experiment it might just work. 这是非常古老的方法,可能会使浏览器崩溃,但是对于本实验来说,它可能只是起作用。

function reloadPage()
  {
  location.reload();
  }

  setInterval(reloadPage,.5);
  1. I assume from using native forEach that you're targeting IE9+, so instead of manually pushing the collection contents into an array you could just: 我假设通过使用本机forEach来定位IE9 +,所以不必手动将集合内容推入数组中,而可以:

     function argsToArray(args) { return Array.prototype.slice.call(args) } 
  2. The rest of the code looks perfectly workable, maybe there's something wrong with the split() or join() arguments. 其余代码看起来完全可行,也许split()join()参数有问题。 Please explain what are you trying to achieve here. 请在这里说明您要达到的目标。

  3. Adding setInterval(argsToArray,500) would just call your first function without any arguments, you should use an anonymous function or pass arguments into the setInterval/setTimeout function (see MDN ). 添加setInterval(argsToArray,500)只会调用没有任何参数的第一个函数,您应该使用匿名函数或将参数传递给setInterval / setTimeout函数(请参见MDN )。

So you want to do something like this? 所以你想做这样的事情?

window.onload=function() {
  var imgs = document.images;
  var tId = setInterval(function() {
    for (var i=0;i<imgs.length;i++) {
      var img = imgs[i];
      var val = 'X0X810D0' + (Math.floor(Math.random()*10)+1);  
      img.src = img.src.replace(/VTlibOlte8YCb/g,val);
    }
  },1000);
}

which is designed replace the src of each image every second - but actually only once since there is no more VTlibOlte8YCb to replace after the first time 它的设计目的是每秒替换每个图像的src-但实际上仅一次,因为第一次之后没有更多的VTlibOlte8YCb可替换

Here is one that does replace the value each time 这是每次都会替换值的值

Live Demo 现场演示

window.onload=function() {
  var imgs = document.images;
  var oldVal = new RegExp(/VTlibOlte8YCb/g);  
  var val = 'X0X810D0' + (Math.floor(Math.random()*10)+1);  
  var tId = setInterval(function() {
    for (var i=0;i<imgs.length;i++) {
      var img = imgs[i];
      val = 'X0X810D0' + (Math.floor(Math.random()*10)+1);  
      img.src = img.src.replace(oldVal,val);
      oldVal = new RegExp("/"+val+"/g");  
    }
  },200);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM