javascript - 使用 jquery 创建动态 html 页面

标签 javascript jquery html jquery-mobile

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

我正在尝试创建一个 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名称,我使用相同的div一切。

这是我的代码:

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

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

示例代码(网站给出的示例代码有 2 个照片库,我扩展了一个以查看 html 元素如何):

enter image description here

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

enter image description here

要放大图像,请按 ctrl + (+)。要返回正常状态,请按 ctrl + (-)

如果您知道 JavaScript 未执行的原因,请留下提示。我尝试解决这个问题已经一个多星期了,但没有成功。非常感谢您阅读到这里。

最佳答案

绑定(bind)事件来动态创建项目应该是这样的。

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

Demo

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

另一个重要注意事项,请勿将 .ready/$(function($) 与 jQuery Mobile 一起使用。使用 jQuery Mobile events

关于javascript - 使用 jquery 创建动态 html 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17407808/

相关文章:

jquery - video.js 完成后更新视频

html - FF 中的 css 显示问题

javascript - 如何在 JSP 页面中使用 Javascript 阻止 HTML 呈现?

数据表过滤器或分页后 JavaScript 不工作

javascript - 将对象数组(构建细节)组合成一个对象(将构建名称作为顶级键)

Javascript计数计时器修改

javascript - 如何在鼠标移动事件时更改窗口中心和图像宽度

javascript - 从其他 HTML 文件加载 HTML 文件中的特定 div

javascript - 自动复制 html 表格内的文本

php - 使用 HTML 输入的标记属性进行 SQL 查询,而不泄露数据库表行 ID