如何在jQuery中访问动态创建的div?

时间:2017-03-06 20:17:36

标签: javascript jquery

我不知道如何调用这个方法,所以如果我错了就纠正我。

我在访问使用.appendTo() jQuery方法创建的div时遇到问题。

这是创建div的代码(我在div类名中添加一个变量):

$divToAppear = $('<div class="photo-element photo'+photoNumber+'"><a href="#" class="remove" title="Remove"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a><div class="progress active"><div class="progress-bar" style="width:0%"></div></div></div>')
$divToAppear.appendTo('.file-upload');

然后,我正在创建一个变量并搜索刚刚创建的div:

$photoElement = $('.file-upload .photo' + imagesUploaded);

当我在一个函数中使用$photoElement时,它无法正常工作且无法访问photo0 div,而是访问它:[prevObject: r.fn.init[1]]

P.S。我可以在不添加变量的情况下访问该div,如下所示:$('.photo0')

HELP! :(

整个功能:

    $(function() {
        var imagesUploaded = 0;
        var imageLimit = 10;

        function appearPhoto(photoNumber) {
            $divToAppear = $('<div class="photo-element photo'+photoNumber+'"><a href="#" class="remove" title="Remove"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a><div class="progress active"><div class="progress-bar" style="width:0%"></div></div></div>')
            $divToAppear.appendTo('.file-upload');
        }

        $(".add-photos-video-btn").click(function(e) {
            if( imagesUploaded >= imageLimit ) {
                return false;
            }

            e.preventDefault();
            var fileHolder  = $(".file-upload");
            var fileInput   = $(".file-upload-input");
            var statusInput = $(".post-input textarea.form-control");
            var postBtn     = $('.buttons button.btn.btn-post');
            var closeBtn    = '<a href="#" class="remove" title="Remove"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a>';
            var cameraBtn   = $('.post-input .appearing-content a.add-photos-video-btn i');
            var videoIcon   = '<span class="glyphicon glyphicon-film file-icon" aria-hidden="true"></span>';
            var audioIcon   = '<span class="glyphicon glyphicon-headphones file-icon" aria-hidden="true"></span>';
            var fileIcon    = '<span class="glyphicon glyphicon-file file-icon" aria-hidden="true"></span>';
            var statusAlert = $('.status-alert');

            $(".file-upload-input").trigger('click');
            $(".file-upload-input:hidden").on('change', function() {
                var isImage         = fileInput.val().match(/(?:jpg|jpeg|bmp|png|gif|tiff)$/igm);
                var isVideo         = $(this).val().match(/(?:3g2|3gp|3gpp|asf|avi|dat|divx|dv|f4v|flv|m2ts|m4v|mkv|mod|mov|mp4|mpe|mpeg|mpeg4|mpg|mts|nsv|ogm|ogv|qt|tod|ts|vob|wmv)$/igm);
                var isAudio         = $(this).val().match(/(?:aif|iff|m3u|m4a|mid|mp3|mpa|ra|wav|wma)$/igm);
                var isFile          = $(this).val().match(/(?:txt|doc|docx|pdf|csv|pps|ppt|pptx|ps|ai|svg|indd|psd|eps)$/igm);
                var fileName        = fileInput.val().split('\\').pop().replace(/.jpg|.jpeg|.bmp|.png|.gif|.tiff/i, '');
                var progressBar     = '<div class="progress active"><div class="progress-bar" style="width:0%"></div></div>';
                var loadingBlocks   = '<div class="loading-blocks"><div class="block"></div><div class="block"></div><div class="block"></div></div>';


                postBtn.prop('disabled', true);
                // fileHolder.empty();
                // fileHolder.css("border-width", "0");
                // $('.update-status-btn').tab('show');
                $(':focus').blur();

                fileHolder.show();

                // $divToAppear = $('<div class="photo-element photo'+imageUploaded+'"><a href="#" class="remove" title="Remove"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a><div class="progress active"><div class="progress-bar" style="width:0%"></div></div></div>')
                // $divToAppear.appendTo(fileHolder);

                appearPhoto(imagesUploaded);
                imagesUploaded++;


                // $("body").on("click", ".photo", function(){
                //     console.log("azaza")
                // });

                $photoElement = $('.file-upload .photo' + imagesUploaded);
                console.log($photoElement);

                // console.log($('.photo'+imagesUploaded) );



                // fileHolder.show().prepend(closeBtn).prepend(progressBar);
                $('.file-upload a.remove').hide();

                // $photoElement.hover(function() {
                //     $(this).has('img').css({"background-color": "#000", "border-color": "#f6f7f8"});
                //     $(this).has('img').find('img').css("opacity", ".7");
                //     $photoElement.find('a.remove').show();
                // }, function() {
                //     $(this).has('img').css({"background-color": "#f6f7f8", "border-color": "rgba(0, 0, 0, 0.1)"});
                //     $(this).has('img').find('img').css("opacity", "1");
                //     $photoElement.find('a.remove').hide();
                // });

                if (isImage) {
                    statusInput.attr("placeholder", "Say something about this photo...");
                    cameraBtn.css("color", "#5b7fd1");
                    $(".progress-bar").stop().animate({
                        width: "100%"
                    }, 3000, function() {
                        setTimeout(function() {
                            $photoElement.find('.progress').remove();
                            $photoElement.prepend(loadingBlocks);
                            // console.log('veikia');
                                var reader = new FileReader();
                                reader.onload = function(e) {
                                    if ($photoElement.find('img').length) {
                                        $photoElement.find('img').attr("src", e.target.result);
                                    } else {
                                        // console.log($photoElement);
                                        $photoElement.append(
                                            $("<img />", {
                                                "src": e.target.result,
                                                "alt": fileName,
                                                "class": "",
                                            })
                                        );
                                    }
                                    $photoElement.each(function() {
                                        var imageUpload = $(this).find('img');
                                        var img = new Image();
                                        img.src = imageUpload[0].src;
                                        img.onload = function() {
                                            $photoElement.find(".loading-blocks").remove();
                                            postBtn.prop('disabled', false);
                                            $photoElement.css("border", "1px solid rgba(0, 0, 0, 0.1)");
                                            $photoElement.find("a.remove").css({"-webkit-text-fill-color": "#dcdcdc", "-webkit-text-stroke-color": "#565a5e"});
                                            $photoElement.find("a.remove").hover(function(){
                                                $(this).css("-webkit-text-fill-color", "#fff");
                                                }, function(){
                                                $(this).css("-webkit-text-fill-color", "#dcdcdc");
                                            });
                                            if (img.width < $photoElement.width() || img.width < img.height) {
                                                $photoElement.find("img").addClass('portrait');
                                            } else {
                                                $photoElement.find("img").removeClass('portrait');
                                            }
                                        }
                                    });
                                }
                                reader.readAsDataURL(fileInput[0].files[0]);

                        }, 300);
                    });
                }
                // else if (isVideo) {
                //     statusInput.attr("placeholder", "Say something about this video...");
                //     fileHolder.find('.progress').remove();
                //     postBtn.prop('disabled', false);
                //     fileHolder.append(videoIcon);
                //     cameraBtn.css("color", "#B3B7BD");
                //     statusInput.focus();
                //     $('.update-status-btn').on('shown.bs.tab', function(e) {
                //         $('.status-box .media-body textarea').focus();
                //     });

                // } else if (isAudio) {
                //     statusInput.attr("placeholder", "Say something about this audio...");
                //     fileHolder.find('.progress').remove();
                //     postBtn.prop('disabled', false);
                //     fileHolder.append(audioIcon);
                //     cameraBtn.css("color", "#B3B7BD");
                //     statusInput.focus();
                //     $('.update-status-btn').on('shown.bs.tab', function(e) {
                //         $('.status-box .media-body textarea').focus();
                //     });

                // } else if (isFile) {
                //     statusInput.attr("placeholder", "Say something about this file...");
                //     fileHolder.find('.progress').remove();
                //     postBtn.prop('disabled', false);
                //     fileHolder.append(fileIcon);
                //     cameraBtn.css("color", "#B3B7BD");
                //     statusInput.focus();
                //     $('.update-status-btn').on('shown.bs.tab', function(e) {
                //         $('.status-box .media-body textarea').focus();
                //     });
                // } else {
                //     statusInput.attr("placeholder", "Say something about this photo...");
                //     cameraBtn.css("color", "#5b7fd1");
                //     $(".progress-bar").stop().animate({
                //         width: "100%"
                //     }, 3000, function() {
                //         setTimeout(function() {
                //             statusAlert.show();
                //                 $('.btn-close').click(function() {
                //                 statusAlert.hide();
                //                 fileHolder.find('.progress').remove();
                //                 postBtn.prop('disabled', false);
                //                 fileHolder.empty().hide();
                //                 cameraBtn.css("color", "#B3B7BD");
                //                 statusInput.attr("placeholder", "What's on your mind?");
                //                 statusInput.focus();
                //             });

                //         }, 1000);
                //     });
                // }
                fileHolder.find('.photo-element a.remove').click(function(e) {
                    e.preventDefault();
                    fileHolder.find('.photo-element').css("background-color", "#f6f7f8");
                    $(".progress-bar").stop(false, true);
                    postBtn.prop('disabled', false);
                    fileHolder.find('.photo-element').empty().hide();
                    fileInput.val("");
                    statusInput.attr("placeholder", "What's on your mind?");
                    cameraBtn.css("color", "#B3B7BD");
                    statusInput.focus();
                });
            }).click(function() {
                $(this).val("");
                if (fileHolder.find('.photo-element .file-icon, img').length === 0) {
                    fileHolder.find('.photo-element').css("background-color", "#f6f7f8");
                    $(".progress-bar").stop(false, true);
                    postBtn.prop('disabled', false);
                    fileHolder.find('.photo-element').empty().hide();
                    statusInput.attr("placeholder", "What's on your mind?");
                    cameraBtn.css("color", "#B3B7BD");
                }
            });
            $('.status-controls').show();
        });

    });

1 个答案:

答案 0 :(得分:1)

调用appearPhoto(imagesUploaded);方法后,您增加了imagesUploaded的值,当您尝试访问$photoElement = $('.file-upload .photo' + imagesUploaded);时,选择器不返回任何内容,因为类'.photo'+imagesUploaded的元素会不存在。要解决此问题,请使用:

$photoElement = $('.file-upload .photo' + (imagesUploaded-1));
console.log($photoElement);