无法将类对象加载到变量中

时间:2016-11-12 21:17:33

标签: javascript jquery

当我尝试在我的.html文件中找到类.galleryImage的所有对象时,一切正常,但是当我想将它放入script.js时,我总是在可变图像中读取0个元素。

 <div id="gallery"></div>
 <script>
 $(function(){
   for(var i = 1; i <= 8; i++){
     var name = 'picture' + i + '.jpg';
     var img =$('<img class="galleryImage" src="picture/'+name+'"/>');
     $('#gallery').append(img);
   }
   var images = $('#gallery').find('.galleryImage');
  console.log(images);
 });
   var g= new PS.Gallery('gallery');
 </script>

功能

(function (ns){
 ns.Gallery = function(id){
  var gallery=$('#' + id);
  console.log(gallery);
  var images = gallery.find('.galleryImage');
  console.log(images);
  images.each(function(idx,el){
  console.log('are u here?');
});
}
}(window.PS = window.PS || {}));

1 个答案:

答案 0 :(得分:0)

我认为你会在这一步得到错误

var g = new PS.Gallery('gallery');

将您的js代码序列更改为此

  (function (ns){
        ns.Gallery = function(id){
            var gallery=$('#' + id);
            console.log(gallery);
            var images = gallery.find('.galleryImage');
            console.log(images);
            images.each(function(idx,el){
                console.log('are u here?');
            });
        }
    }(window.PS = window.PS || {}));
    $(function(){
        for(var i = 1; i <= 8; i++){
            var name = 'picture' + i + '.jpg';
            var img =$('<img class="galleryImage" src="picture/'+name+'"/>');
            $('#gallery').append(img);
        }
        var images = $('#gallery').find('.galleryImage');
        console.log(images);
    });

        var g= new PS.Gallery('gallery');

PS:查看代码段

 (function (ns){
        ns.Gallery = function(id){
            var gallery=$('#' + id);
           // console.log(gallery);
            var images = gallery.find('.galleryImage');
           // console.log(images);
            images.each(function(idx,el){
                //console.log('are u here?');
            });
        }
    }(window.PS = window.PS || {}));
    $(function(){
        for(var i = 1; i <= 8; i++){
            var name = 'picture' + i + '.jpg';
            var img =$('<img class="galleryImage" src="picture/'+name+'"/>');
            $('#gallery').append(img);
        }
        var images = $('#gallery').find('.galleryImage');
        console.log(images.length);

    });
    var g= new PS.Gallery('gallery');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="gallery"></div>

在此更改后,一切都将按预期工作。这是因为函数提升:函数声明不只是提升函数的名称。它还提升了实际的功能定义。

希望这有帮助