javascript 使用 jquery 创建动态 html 页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17407808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:12:42  来源:igfitidea点击:

Dynamic html page creation with jquery

javascriptjqueryhtmljquery-mobile

提问by Johny Jaz

I will try to keep this post the shortest possible.

我会尽量保持这篇文章的最短。

I am trying to create a jquery mobile web-page where , i import the photos and albums from a facebook page , using the facebook javascript sdk , and show them to my page. I also use the PhotoSwipeplugin to get the albums show nicely with carousel effects etc. You dont need to have any knowledge on the plugin or the sdk to help, as i can tell you exactly where is my problem and you only need to know javascript/jquery.

我正在尝试创建一个 jquery 移动网页,我从 facebook 页面导入照片和相册,使用 facebook javascript sdk,并将它们显示到我的页面。我还使用PhotoSwipe插件来让相册通过轮播效果等很好地显示出来。你不需要对插件或 sdk 有任何帮助,因为我可以确切地告诉你我的问题在哪里,你只需要知道 javascript /jquery.

My problem is that i do import the albums and show them to the user but i cant get the carousel effect of the plugin. From the example code of the plugin , when a user selects a picture this code is executed:

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

$(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));

I use the same code(i use .on on my code) to my "dynamically-generated" web-page but it seems that the code inside $('div.gallery-page')is NEVER executed. And i really cant figure out why , as the page that i generate is identical to the example page. I give the same classnames, i use the same divseverything.

我对我的“动态生成”网页使用相同的代码(我在我的代码上使用 .on),但似乎里面的代码$('div.gallery-page')从未执行过。我真的不知道为什么,因为我生成的页面与示例页面相同。我给相同的class名字,我使用相同的divs一切。

This is my code :

这是我的代码:

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

I think the important part here is this:

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

 $("#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> ');

where as you can see i give the correct class name class="gallery-page"to every dynamically generated div.

如您所见,我class="gallery-page"为每个动态生成的 div提供了正确的类名。

I will also give here 2 screenshots when debugging with chrome , one from the example code that is working and one from my code , just to show you that the elements on the final html page look identical..

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

Example code(the example code given from the site has 2 galleries of photos , i expanded one to see how are the html elements):

示例代码(该站点给出的示例代码有 2 张照片画廊,我展开了一张照片以查看 html 元素如何):

enter image description here

在此处输入图片说明

My code(because i import the albums from a facebook page , here we have a lot more galleries. Again i expand one of them to show you that the html elements are identical to the example , and i use the same classes and divs):

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

enter image description here

在此处输入图片说明

In order to enlarge the images press ctrl + (+). To go back to normal press ctrl + (-).

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

If you have ANY idea why the javascript is not executed , please leave a hint. I am trying to fix this for more than a week without any success. Thank you very very much for reading till here.

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

回答by Brad M

live()is removed from jQuery 1.9, and I see this tag in your code.

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

jquery-1.9.1.min.js

回答by Omar

Binding events to dynamically create items should be like this.

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

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

Demo

演示

This code applies for all types of dynamic elements.

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

Another important note, don't use .ready/ $(function($)with jQuery Mobile. Use jQuery Mobile events.

另一个重要的注意事项,不要在 jQuery Mobile 中使用.ready/ $(function($)。使用 jQuery Mobile事件

回答by anacarolinats

You must change where you use liveby on

你必须改变你使用live的地方on

$(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;

    });

});

documentation: http://api.jquery.com/on/

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