简体   繁体   English

将随机网址从文件动态加载到iframe

[英]Dynamically load random url from file into iframe

First of all, this is supposed to be running offline as a web page in my browser and should work without additional installs like php. 首先,这应该在我的浏览器中作为网页脱机运行,并且无需安装诸如php即可运行。

I have an iframe which content should be randomly loaded. 我有一个iframe,内容应随机加载。

I have: 我有:

  • /index.html (the page with the Iframe) /index.html(包含iframe的页面)
  • /files.txt (a file with a list of relative urls) /files.txt(包含相对网址列表的文件)

and tons of .html files (also in subfolders). 和大量的.html文件(也在子文件夹中)。
For each of these files exists an entry in files.txt with it's exact relative path. 对于这些文件中的每一个,在files.txt中都存在一个具有确切相对路径的条目。

If I wouldn't have so many files, I would just make an hardcoded javascript array with the relative urls and take a random entry from that array as source for the iframe. 如果我没有那么多文件,我只需要制作一个带有相对URL的硬编码javascript数组,然后从该数组中随机抽取一个条目作为iframe的源即可。 But I'm talking about >6000 files. 但是我说的是> 6000个文件。 So how can I do that? 那我该怎么办呢?

You can use jQuery to load file list via AJAX, split it by \\n and set random line as an src for iframe: 您可以使用jQuery通过AJAX加载文件列表,将其用\\n分割,然后将随机行设置为iframe的src

$.ajax({
  url: 'files.txt',
  success: function(text) {
    var fileList = text.split('\n');
    var randomIndex = randomInt(0, fileList.length - 1);    

    $('iframe').attr('src', fileList[randomIndex]);
  }
});

function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

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

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