我有这个剧本

<script type="text/javascript">
   $(document).ready(function() {
      $("a[rel='Hotel']").colorbox({
         maxWidth: "90%",
         maxHeight: "90%",
         opacity: ".5"
      });
      $("a[rel='Rooms']").colorbox({
         maxWidth: "90%",
         maxHeight: "90%",
         opacity: ".5"
      });
   });
</script>


其中Hotel和Rooms是我在galleries文件夹中的两个文件夹的名称。

我要实现的自动化文件夹创建的目标。例如:

<script type="text/javascript">
   $(document).ready(function() {
      $("a[rel='Hotel']").colorbox({
         maxWidth: "90%",
         maxHeight: "90%",
         opacity: ".5"});
      $("a[rel='Rooms']").colorbox({
         maxWidth: "90%",
         maxHeight: "90%",
         opacity: ".5"});
      $("a[rel='Another Name']").colorbox({
         maxWidth: "90%",
         maxHeight: "90%",
         opacity: ".5"});
      $("a[rel='Another Name']").colorbox({
         maxWidth: "90%",
         maxHeight: "90%",
         opacity: ".5"
      });
   });
</script>


我曾尝试使用类似的方法,但是没有用

  <script type="text/javascript">
     $(document).ready(function() {
        function listFolderFiles($dir) {
           $ffs = scandir($dir);
                   foreach($ffs as $ff){
           if ($ff != '.' && $ff != '..'){
           echo "$('a[rel='$ff']').colorbox({maxWidth: '90%', maxHeight: '90%', opacity: '.5'});";
        }
        }
     }

     listFolderFiles('galleries');
     });
  </script>


任何帮助将不胜感激

最佳答案

如果您使用的是纯JS,则只需使用for语句并从数组中提取:

var strings = ['Hotel', 'Room'];
for(var i = 0; i < strings.length; i++){
    $("a[rel='" + strings[i] + "']").colorbox({
        maxWidth: "90%",
        maxHeight: "90%",
        opacity: ".5"
    });
}


根据OP要求

function addType(name){
    $("a[rel='" + name + "']").colorbox({
        maxWidth: "90%",
        maxHeight: "90%",
        opacity: ".5"
    });
}


编辑

与OP解决方案讨论后,如下所示:

$(document).ready(function() {
    function listAdd(){

        <?
        $dir = "galleries/";

        // Sort in ascending order - this is default
        $folders = scandir($dir);
        echo 'var folders = ', json_encode($folders);echo ';';
        ?>

        if(folders[0] == '.') folders.shift();
        if(folders[0] == '..') folders.shift();
        for(var i = 0; i < folders.length; i++){
            $("a[rel='" + folders[i] + "']").colorbox({
                maxWidth: "90%",
                maxHeight: "90%",
                opacity: ".5"
            });
        }
    }
    listAdd();
});

关于javascript - 获取函数中的文件夹名称,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23156310/

10-12 00:14
查看更多