无法选择从文件加载的追加图像

时间:2019-03-24 12:46:37

标签: javascript jquery twitter-bootstrap bootstrap-4

我正在使用以下脚本从文件夹加载图像并将其附加到div:

$(function() {
    var folder = "img/moreprojects/";

    $.ajax({
        url : folder,
        success: function (data) {
            $(data).find("a").attr("href", function (i, val) {
                if( val.match(/\.(jpe?g|png|gif)$/) ) {
                    $("#gallery").append( "<div class=\"col-12 col-sm-3\" align='center'><img class='img-fluid img-thumbnail img-rounded mx-auto d-block' style=\"max-width: 240px; max-height: 240px; margin: 12px;\" src='"+ folder + val +"'></div>" );
                }
            });
        }
    });
});

但是,当我调用我的下一个脚本时,该脚本打开了图像的模型(适用于页面上已存在的图像),图像无法打开:

$(function() {
    $('img').on('click', function() {
        $('.enlargeImageModalSource').attr('src', $(this).attr('src'));
        $('#enlargeImageModal').modal('show');
    });
});

我如何拥有已经适用于HTML图像的此功能,适用于动态加载的图像的功能?

注意::我正在使用Bootstrap 4和jQuery。

编辑

HTML结构(我正在使用Bootstrap 4):

<section class="py-5">
        <div class="container">
            <div class="row" id="gallery">
                <p class="lead">Welcome to our gallery! Here we showcase all the images from our projects and other work. Use the toggles below, to switch between a list view and a swiping gallery view!</p>
                <br /><br />
            </div>
        </div>
    </section>

<div class="modal fade" id="enlargeImageModal" tabindex="-1" role="dialog" aria-labelledby="enlargeImageModal" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="modal-body">
                    <img src="" class="enlargeImageModalSource" style="width: 100%;">
                </div>
            </div>
        </div>
    </div>

1 个答案:

答案 0 :(得分:0)

从以下位置更改.on('click', ...)呼叫:

$('img').on('click', function() {...});

$(document).on('click', 'img', function() {...});

解决了在动态加载的图片上调用click事件的问题。