繁体   English   中英

使用jQuery动态创建HTML页面

[英]Dynamic html page creation with jquery

我将尽力使这篇文章尽可能短。

我正在尝试创建一个jquery移动网页,其中,我使用facebook javascript sdk从facebook页面导入照片和相册,并将它们显示在我的页面上。 我还使用PhotoSwipe插件使相册具有轮播效果等很好地显示。 您不需要对插件或sdk有任何了解即可提供帮助 ,因为我可以确切地告诉您我的问题在哪里,而您只需要了解javascript / jquery。

我的问题是我确实导入了相册并将其显示给用户,但是我无法获得插件的轮播效果 从插件的示例代码中,当用户选择图片时,将执行以下代码:

$(document).ready(function(){

                $('div.gallery-page')
                    .live('pageshow', function(e){
                        var 
                            currentPage = $(e.target),
                            options = {},
                            photoSwipeInstance = $("ul.gallery a", e.target).photoSwipe(options,  currentPage.attr('id'));

                        return true;

                    })

                    .live('pagehide', function(e){

                        var 
                            currentPage = $(e.target),
                            photoSwipeInstance = PhotoSwipe.getInstance(currentPage.attr('id'));

                        if (typeof photoSwipeInstance != "undefined" && photoSwipeInstance != null) {
                            PhotoSwipe.detatch(photoSwipeInstance);
                        }

                        return true;

                    });

            });

        }(window, window.jQuery, window.Code.PhotoSwipe));

我在“动态生成的”网页上使用了相同的代码(我在代码上使用.on),但是似乎从未执行过$('div.gallery-page')内部的代码。 我真的不知道为什么,因为我生成的页面与示例页面相同。 我给相同的class名,所有东西都使用相同的divs

这是我的代码:

<!DOCTYPE html> 
<html>
<head>
    <meta charset="utf-8">
    <title>CityInfo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
    <link href="photoSwipe/jquery-mobile.css" type="text/css" rel="stylesheet" />
    <link href="photoSwipe/photoswipe.css" type="text/css" rel="stylesheet" />

    <script type="text/javascript" src="photoSwipe/klass.min.js"></script>  
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
    <script type="text/javascript" src="photoSwipe/code.photoswipe.jquery-3.0.5.min.js"></script>

    <script type="text/javascript">
        //PhotoSwipe
        /*
         * IMPORTANT!!!
         * REMEMBER TO ADD  rel="external"  to your anchor tags. 
         * If you don't this will mess with how jQuery Mobile works
         */
        (function(window, $, PhotoSwipe){
            $(document).ready(function(){
                $('div.gallery-page')
                    .on('pageshow', function(e){
                        var 
                            currentPage = $(e.target),
                            options = {},
                            photoSwipeInstance = $("ul.gallery a", e.target).photoSwipe(options,  currentPage.attr('id'));  
                        return true;    
                    })

                    .on('pagehide', function(e){
                        var 
                            currentPage = $(e.target),
                            photoSwipeInstance = PhotoSwipe.getInstance(currentPage.attr('id'));
                        if (typeof photoSwipeInstance != "undefined" && photoSwipeInstance != null) {
                            PhotoSwipe.detatch(photoSwipeInstance);
                        }
                        return true;    
                    }); 
            });
        }(window, window.jQuery, window.Code.PhotoSwipe));
    </script>

</head> 

<body> 

    <div id="fb-root"></div>
    <script>
        var albumPhotos = new Array();
        var albumThumbnails = new Array();
        // start the entire process
        window.fbAsyncInit = function() {
            // init the FB JS SDK 
            FB.init({
                appId      : '564984346887426',                                                  // App ID from the app dashboard
                channelUrl : 'channel.html',                       // Channel file for x-domain comms
                status     : true,                                                               // Check Facebook Login status
                xfbml      : true                                                                // Look for social plugins on the page
            });

            FB.api('169070991963/albums', checkForErrorFirst(getAlbums));

        }


        // checkForErrorFirst wraps your function around the error checking code first
        // if there is no response, then your code will not be called
        // this allows you to just write the juicy working code 
        //   and not worry about error checking
        function checkForErrorFirst(myFunc) {
            return function(response) { 
                if (!response || response.error) {
                    alert("Noo!!");
                } else {
                    myFunc(response);
                }
            };
        }


        function getAlbums(response) {
            for (var i=0; i < response.data.length; ++i) {
                processAlbum(response.data[i], i);
            } 
        }


        function processAlbum(album, i) {
            FB.api(album.id + "/photos", checkForErrorFirst(populateAlbum(album, i)));
        }


        function populateAlbum(album, i) {
            return function(response) {
                for (var k=0; k < response.data.length; ++k){ 
                    albumThumbnails[i] =  albumThumbnails[i]||[];
                    albumThumbnails[i][k] = response.data[k].picture;
                    albumPhotos[i] = albumPhotos[i]||[];
                    albumPhotos[i][k] = response.data[k].source;
                }

                // now that we've populated the album thumbnails and photos, we can render the album
                FB.api(album.cover_photo, checkForErrorFirst(renderAlbum(album, i)));
            };
        }

        function renderAlbum(album, i) {
            return function(response) {
                var albumName = album.name;
                var albumCover = album.cover_photo;
                var albumId = album.id;
                var numberOfPhotos = album.count;

               // render photos
               $(".albums").append('<li>'+
               '<a href="#Gallery' + i + '"' + 'data-transition="slidedown">'+
               '<img src= "' + response.picture + '"  />'+
               '<h2>' + albumName + '</h2>'+
               '<p>' + "Number of Photos:  " + numberOfPhotos +'</p>'+
               '</a>'+
               '</li>').listview('refresh');

               $("#Home").after('<div data-role="page" data-add-back-btn="true" id=Gallery'+ i +
               ' class="gallery-page"> ' +
               ' <div data-role="header"><h1>Gallery</h1></div> ' + ' <div data-role="content"> ' +
               ' <ul class="gallery"></ul> ' + ' </div> ' +
               ' </div> ');

               for(var x=0; x < albumPhotos[i].length; x++)
                    $('#Gallery' + i + ' .gallery').append('<li><a href="' + albumPhotos[i][x] 
                    + '"  rel="external"><img src="' +  albumThumbnails[i][x] + '"' + '/> </a> </li>');
             };
        }

        // Load the SDK asynchronously
        (function(d, s, id){
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) {return;}
            js = d.createElement(s); js.id = id;
            js.src = "//connect.facebook.net/en_US/all.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));

    </script>



    <div data-role="page" id="Home" data-theme="c">
        <div data-role="content">
            <h2 id="banner" align = "center">Photo Albums</h2>
            <ul data-role="listview" data-inset="true" class="albums">      
            </ul> 
        </div>      
    </div>



</body>
</html>

我认为这里的重要部分是:

 $("#Home").after('<div data-role="page" data-add-back-btn="true" id=Gallery'+ i +
               ' class="gallery-page"> ' +
               ' <div data-role="header"><h1>Gallery</h1></div> ' + ' <div data-role="content"> ' +
               ' <ul class="gallery"></ul> ' + ' </div> ' +
               ' </div> ');

如您所见,在这里我给每个动态生成的div正确的类名class="gallery-page"

在使用chrome进行调试时,我还将在此处提供2个屏幕截图,其中一个来自正在工作的示例代码,另一个来自我的代码,只是为了向您展示最终html页面上的元素看起来是相同的。

示例代码(该站点提供的示例代码有2张照片,我将其中一张放大为html元素):

在此处输入图片说明

我的代码(因为我是从facebook页面导入相册的,所以在这里我们有很多画廊。再次,我扩展其中一个画廊,向您展示html元素与示例相同,并且我使用相同的类和div):

在此处输入图片说明

为了放大图像,请按ctrl +(+)。 要恢复正常,请按ctrl +(-)

如果您有任何想法为什么不执行javascript,请留下提示。 我试图解决这个问题超过一个星期,但没有成功。 非常感谢您阅读到这里。

live()已从jQuery 1.9中删除,我在您的代码中看到此标记。

jquery-1.9.1.min.js

绑定事件以动态创建项目应该是这样的。

$(document).on('event', '.element', function () { magic });

演示版

该代码适用于所有类型的动态元素。

另一个重要说明,不要在jQuery Mobile中使用.ready / $(function($) 。请使用jQuery Mobile events

您必须更改在您使用liveon

$(document)
    .on('pageshow', 'div.gallery-page', function(e){
        var
                currentPage = $(e.target),
                options = {},
                photoSwipeInstance = $("ul.gallery a", e.target).photoSwipe(options,  currentPage.attr('id'));
        return true;
    })

    .on('pagehide', 'div.gallery-page', function(e){
        var 
            currentPage = $(e.target),
            photoSwipeInstance = PhotoSwipe.getInstance(currentPage.attr('id'));

        if (typeof photoSwipeInstance != "undefined" && photoSwipeInstance != null) {
             PhotoSwipe.detatch(photoSwipeInstance);
        }

        return true;

    });

});

文档: http : //api.jquery.com/on/

暂无
暂无

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

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