获取函数内的文件夹名称

时间:2014-04-18 14:38:25

标签: javascript

我有这个脚本

<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是我在gallery库文件夹中的两个文件夹的名称。

我希望实现自动创建文件夹的目的。例如:

<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>

非常感谢任何帮助

1 个答案:

答案 0 :(得分:3)

如果您使用的是纯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();
});