JavaScript 自动创建 iframe

JavaScript Automated Iframe Creation

本文关键字:iframe 创建 JavaScript      更新时间:2023-09-26

我需要知道如何根据目录中的html文件数量自动创建Iframe。假设我在main.html所在位置的子目录中1.html2.html。我想自动创建 2 个 Iframe(main.html 个),一个显示1.html,另一个显示2.html。顺便说一句,如果你不知道,2.html1.html是本地文件

尝试像这样实现:

$.ajax({
    url: "/images-folder-on-server/",
    success: function (data) {
        var file_count = $(data).length();
        $.each( data, function( key, value ) {
           appendIframe(value);
        });
    }
});
function appendIframe( file)
{
   var iframe = document.createElement('iframe');
   iframe.src = file;
   iframe.style.width = "100px";
   iframe.style.height = "100px";
   document.body.appendChild(iframe);
}

对服务器进行 ajax 调用以获取目录中的文件列表

httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function(){
   //iterate the list and call addIframe( src ) for each of them 
};
httpRequest.open('GET', "listFilesInDirectory");
httpRequest.send();

这就是addIframe的样子

function addIframe( src )
{
   var iframe = document.createElement('iframe');
   iframe.src = src;
   iframe.style.width = "640px";
   iframe.style.height = "px";
   document.body.appendChild(iframe);
}
addIframe( "subdir/1.html" );
addIframe( "subdir/2.html" );
我认为

问题不在于如何使用Javascript创建iFrame,而在于计算使用它的文件。我建议创建对服务器端语言的ajax请求来计算文件的数量,然后您可以使用该数字使用jQuery创建iFrame元素。您可以使用以下用PHP编写的代码作为服务器端脚本:-

<?php
function getNoFiles(){
    $i = 0;
    $dir = 'yourHTMLDirectory/';
    if ($handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false){
            if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
                $i++;
        }
    }
echo $i;
  }
?>

您可以在简单循环下使用这样的jQuery简单代码进行创建,限制从PHP代码中获取计数。

$('<your iframe tag></iframe>').appendTo('your div or area class or id');