How to use bootstrap modal on multiple images on same page on image click?

后端 未结 4 1149
夕颜
夕颜 2020-12-21 10:39

I have about 18 images on the page that I am trying to display larger in a modal upon clicking the image, but it only displays the first image every time.

I have tri

4条回答
  •  既然无缘
    2020-12-21 11:24

    You are very close to your goal, you have 2 images

    Text dollar code part one.
    Text dollar code part one.
    

    One Modal

    
    

    If you want to show image in modal with your approach using click function

    $(document).ready(function () {
        $('img').on('click', function () {
            var image = $(this).attr('src');
            $('#myModal').on('show.bs.modal', function () {
                $(".img-responsive").attr("src", image);
            });
        });
    });
    

    Fiddle


    Or you can use bootstrap modal event function only, less complicated and better approach (recommended solution)

    $(document).ready(function () {
            $('#myModal').on('show.bs.modal', function (e) {
                var image = $(e.relatedTarget).attr('src');
                $(".img-responsive").attr("src", image);
            });
    });
    

    Fiddle

提交回复
热议问题