同位素和javascript - 添加新元素

时间:2018-05-20 20:24:34

标签: javascript jquery-isotope

我试图创建一个从json(不是真正的json,更像是javascript数组)加载的图像表,每次json更改时(当我将一个新图像附加到json文件时)脚本,我想要上传我的图像表。

这是json格式:

[{
    "image": "images/set_1_UTC+03.jpg",
    "weight": 101
}, {
    "image": "images/set_1_UTC+03.jpg",
    "weight": 102
}, {
    "image": "images/set_1_UTC+03.jpg",
    "weight": 103
}, {
    "image": "images/set_1_UTC+03.jpg",
    "weight": 104
}]

为此,我使用同位素。我设法实现了上面提到的所有内容,唯一的问题是我想让图像可以点击,每当我点击其中一个图像时,让它的尺寸更大,当我再次点击它以回到小尺寸。这是代码:

<script>
    var previous = 0;
    var current = 0;
    loadJSON(function(response) {
        // Parse JSON string into object
        current = JSON.parse(response);
    });

    function loadJSON(callback) {
        var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
        xobj.open('GET', 'data.json', true); // Replace 'my_data' with the path to your file
        xobj.onreadystatechange = function() {
            if (xobj.readyState == 4 && xobj.status == "200") {
                // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
                callback(xobj.responseText);
            }
        };
        xobj.send(null);
    }

    let lengthOfprevious = previous.length;

    setInterval(function() {
        loadJSON(function(response) {
            // Parse JSON string into object
            current = JSON.parse(response);
        });
        previous = current;
        if (lengthOfprevious != current.length) {
            UpdateBody(lengthOfprevious);
        }
        lengthOfprevious = previous.length;
    }, 5000);

    function UpdateBody(startIndex) {
        var newElements = "";
        for (let i = startIndex; i < previous.length; i++) {
            $(document).ready(function() {
                newElements = "";
                newElements +=
                    '<div class="photo element-item">' +
                    '<a href="' + previous[i].image + '"><img class="small-image" src="' + previous[i].image + '"/></a>' +
                    '<a class="weight">' + previous[i].weight + '</a></div>';
                var $newElems = $(newElements);

                $('#container').append($newElems).imagesLoaded(function() {

                    $('#container').isotope('insert', $newElems);
                });
            });
        }

        // ============//
        $(function() {
            var $container = $('#container'),
                $photos = $container.find('.photo'),
                $loadingIndicator = $('<div class="loading"><span><img src="http://i.imgur.com/IE7iw.gif" /></span></div>');
            // trigger Isotope after images have loaded
            $container.imagesLoaded(function() {
                $container.isotope({
                    itemSelector: '.photo',
                    masonry: {
                        columnWidth: 200
                    }
                });
            });
            // shows the large version of the image
            // shows small version of previously large image
            function enlargeImage($photo) {
                $photos.filter('.large').removeClass('large');
                $photo.addClass('large');
                $container.isotope('reLayout');
            }

            $photos.find('a').click(function() {
                var $this = $(this),
                    $photo = $this.parents('.photo');

                if ($photo.hasClass('large')) {
                    // already large, just remove
                    $photo.removeClass('large');
                    $container.isotope('reLayout');
                } else {
                    if ($photo.hasClass('has-big-image')) {
                        enlargeImage($photo);
                    } else {
                        // add a loading indicator
                        $this.append($loadingIndicator);

                        // create big image
                        var $bigImage = $('<img>', {
                            src: this.href
                        });

                        // give it a wrapper and appended it to element
                        $('<div>', {
                                'class': 'big-image'
                            })
                            .append($bigImage)
                            .appendTo($this)
                            .imagesLoaded(function() {
                                $loadingIndicator.remove()
                                enlargeImage($photo);
                            });
                        // add a class, so we'll know not to do this next time
                        $photo.addClass('has-big-image');
                    }
                }
                return false;
            });
        });
    }
</script>

问题是setInterval运行一次之后,一切都按预期工作,当它再次运行时,图像不再可点击。如果我在for中删除// ============ //标签之后的部分,则只能点击最后一张图片。

我无法找到解决方案(我是javascript的初学者)。有人能指出我正确的方向吗?

更新Here您可以获取项目的存档,以便可以在本地运行。

您需要手动复制并粘贴数据文件中的某些行以使演示生效,因为它会搜索先前状态与数据文件当前状态的差异。问题是它首先是可点击的,然后它就不再可以了。

3 个答案:

答案 0 :(得分:3)

我在代码中发现了一些需要修改的内容:

  1. 为什么$(document).ready使用时间超过1次?
  2. 无需使用$(function()
  3. 因为我看到照片类是在运行时动态生成的,而容器类已经在DOM中了,所以我修改了click事件

    $container.on('click', '.photo a', function() {
    
  4. 修改请注意代码未经过测试;我刚刚修改了代码。

    最终更新的代码如下:

    var previous = 0;
    var current = 0;
    loadJSON(function(response) {
        // Parse JSON string into object
        current = JSON.parse(response);
    });
    
    function loadJSON(callback) {
        var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
        xobj.open('GET', 'data.json', true); // Replace 'my_data' with the path to your file
        xobj.onreadystatechange = function() {
            if (xobj.readyState == 4 && xobj.status == "200") {
                // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
                callback(xobj.responseText);
            }
        };
        xobj.send(null);
    }
    let lengthOfprevious = previous.length;
    
    setInterval(function() {
        loadJSON(function(response) {
            // Parse JSON string into object
            current = JSON.parse(response);
        });
        previous = current;
        if (lengthOfprevious != current.length) {
            UpdateBody(lengthOfprevious);
        }
        lengthOfprevious = previous.length;
    }, 5000);
    
    function UpdateBody(startIndex) {
        var newElements = "",
            $container = $('#container'),
            $photos = $container.find('.photo'),
            $loadingIndicator = $('<div class="loading"><span><img src="http://i.imgur.com/IE7iw.gif" /></span></div>');
    
        $(document).ready(function() {
            for (let i = startIndex; i < previous.length; i++) {
                newElements = "";
                newElements +=
                    '<div class="photo element-item">' +
                    '<a href="' + previous[i].image + '"><img class="small-image" src="' + previous[i].image + '"/></a>' +
                    '<a class="weight">' + previous[i].weight + '</a></div>';
    
                var $newElems = $(newElements);
    
                $container.append($newElems).imagesLoaded(function() {
                    $container.isotope('insert', $newElems);
                });
            }
            $container.imagesLoaded(function() {
                $container.isotope({
                    itemSelector: '.photo',
                    masonry: {
                        columnWidth: 200
                    }
                });
            });
            // shows the large version of the image
            // shows small version of previously large image
            function enlargeImage($photo) {
                $photos.filter('.large').removeClass('large');
                $photo.addClass('large');
                $container.isotope('reLayout');
            }
    
            $container.on('click', '.photo a', function() {
                var $this = $(this),
                    $photo = $this.parents('.photo');
    
                if ($photo.hasClass('large')) {
                    // already large, just remove
                    $photo.removeClass('large');
                    $container.isotope('reLayout');
                } else {
                    if ($photo.hasClass('has-big-image')) {
                        enlargeImage($photo);
                    } else {
                        // add a loading indicator
                        $this.append($loadingIndicator);
    
                        // create big image
                        var $bigImage = $('<img>', {
                            src: this.href
                        });
    
                        // give it a wrapper and appended it to element
                        $('<div>', {
                                'class': 'big-image'
                            })
                            .append($bigImage)
                            .appendTo($this)
                            .imagesLoaded(function() {
                                $loadingIndicator.remove()
                                enlargeImage($photo);
                            });
    
                        // add a class, so we'll know not to do this next time
                        $photo.addClass('has-big-image');
    
                    }
                }
    
                return false;
            });
    
        });
    }
    

答案 1 :(得分:1)

您可以将脚本块替换为以下脚本块,然后尝试运行:

<script>
    var previous = [];
    var current = [];

    function loadJSON(callback) {
        var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
        xobj.open('GET', 'data.json', true); // Replace 'my_data' with the path to your file
        xobj.onreadystatechange = function() {
            if (xobj.readyState == 4 && xobj.status == "200") {
                // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
                callback(xobj.responseText);
            }
        };
        xobj.send(null);
    }

    function start(){
        loadJSON(function(response) {
            previous = current;
            current = JSON.parse(response);
            if (previous.length != current.length) {
                UpdateBody(current);
            }
        });
    }

    function UpdateBody(data) {
        var newElements = "";
        for (var i in data) {            
            newElements +=
                '<div class="photo element-item">' +
                '<a href="' + data[i].image + '"><img class="small-image" src="' + data[i].image + '"/></a>' +
                '<br/>' +
                '<a class="weight">' + data[i].weight + '</a>' +
                '</div>';
        }

        if(newElements!=""){
            var $newElems = $(newElements);

            $('#container').append($newElems).imagesLoaded(function() {
                $('#container').isotope('insert', $newElems);
            });
        }
    }

    $(document).ready(function(){
        start();

        setInterval(start, 5000);

        var $container = $('#container'),
                $photos = $container.find('.photo'),
                $loadingIndicator = $('<div class="loading"><span><img src="http://i.imgur.com/IE7iw.gif" /></span></div>');
        // trigger Isotope after images have loaded
        $container.imagesLoaded(function() {
            $container.isotope({
                itemSelector: '.photo',
                masonry: {
                    columnWidth: 200
                }
            });
        });
        // shows the large version of the image
        // shows small version of previously large image
        function enlargeImage($photo) {
            $container.find('.photo.large').removeClass('large');
            $photo.addClass('large');
            $container.isotope('layout');
        }

        $(document).on('click','#container .photo a',function() {
            var $this = $(this),
                $photo = $this.parent('.photo');

            if ($photo.hasClass('large')) {
                // already large, just remove
                $photo.removeClass('large');
                $container.isotope('layout');
            } else {
                if ($photo.hasClass('has-big-image')) {
                    enlargeImage($photo);
                } else {
                    // add a loading indicator
                    $this.append($loadingIndicator);

                    // create big image
                    var $bigImage = $('<img>', {
                        src: this.href
                    });

                    // give it a wrapper and appended it to element
                    $('<div>', {
                            'class': 'big-image'
                        })
                        .append($bigImage)
                        .appendTo($this)
                        .imagesLoaded(function() {
                            $loadingIndicator.remove()
                            enlargeImage($photo);
                        });
                    // add a class, so we'll know not to do this next time
                    $photo.addClass('has-big-image');
                }
            }
            return false;
        });
    });
</script>

我对您的代码进行了很多更改。这帮助我组织了代码。但是点击不起作用的最重要部分是:

$(document).on('click','#container .photo a',function() {

我像上面一样附加了click事件处理程序,因为元素是在页面加载后添加的。因此它需要处理在附加处理程序之后添加的元素。

您可以阅读有关jQuery.on函数的更多信息,并尝试了解其工作原理。

答案 2 :(得分:0)

$photos.find('a').click(中的问题 - 此绑定点击现有项目,因此新的不会触发点击。你应该参加活动代表团&amp;

$('.items_wrap_class').on('click', 'a', function() { /* all existings an new items clicks will fire this */ })

UPD

在您的情况下,请委托#container .photo a点击处理。

替换 $photos.find('a').click( function() { ... })

$('#container').on('click', '.photo a', function() { ... })