简体   繁体   中英

How to assign URL to src attribute before append the HTML code in jQuery

I need an answer to this strange situation. I'll try to explain as clean as possible. I'm trying to generate this piece of HTML code (I will call it to template for now) using jQuery.

In the image tag I'm using an src already, to check can I get the URL with created HTML but it's not necessary unless debugging.

         <script id="previewImg" type="text/html">
             <div class="position-relative">
                  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/2017_Ford_Mustang_%2844528207214%29.jpg/375px-2017_Ford_Mustang_%2844528207214%29.jpg" class="uploaded-img-preview border-radius-lg shadow text-center" />
                 <div class="rounded-circle uploaded-file-remove-btn">
                     <span class="fa fa-trash text-white"></span>
                 </div>
             </div>
         </script>

Here you can see the core codes nothing strange just a few variable declarations, initial methods, etc. Everything works fine. As you can guess alert works and shows us the URL ( https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/2017_Ford_Mustang_%2844528207214%29.jpg/375px-2017_Ford_Mustang_%2844528207214%29.jpg )


        const totalImageCount = 3;
        let uploadedFileURLs;

        $(document).ready(function () {
            uploadedFileURLs = new Array();
            previewImages = new Array();
            alert("src of image   " + $($("#previewImg").html()).find("img").attr("src"));
        });


        $(function () {
            $('#img-upload').change(function (event) {
                for (let i = uploadedFileURLs.length; i < event.target.files.length; i++) {
                    let url = URL.createObjectURL(event.target.files[i]);
                    uploadedFileURLs.push(url);
                }

                UpdatePreviewImages();
            });
        })

but... if you look at that part of my code. That's the dark magic I just spent around 5 hours (I'm a newbie at js and jQuery) but still, it's not working. Still, I'm not able to assign src for created (links are not null ofc I checked all of them again and again) The line which I specify (this line comment) does not assign the value. When I look at the page source it shows me the img tag's src attribute as src(unknown)

        function UpdatePreviewImages() {
          for (var i = 0; i < uploadedFileURLs.length; i++) {
            let previewImg = $("#previewImg").html();
            $($(previewImg).html()).find("img").attr("src", uploadedFileURLs[i]); // this line
            $("#previewImageContainer").append(previewImg);
          }
        }

But if I append the template (a few HTML elements) first, then assign the src value. It does assign. And the problem is here is, it will assign the same URL for all created templates' img elements' src. For example, if you upload 3 photos all of them will appear as the last photo you selected.

        function UpdatePreviewImages() {
          for (var i = 0; i < uploadedFileURLs.length; i++) {
            let previewImg = $("#previewImg").html();
            let createdImg = $("#previewImageContainer").append(previewImg);
            $(createdImg).find("img").attr("src", uploadedFileURLs[i]); // this line
           }
         }

What's the point I'm missing?

Better to use the regular querySelectors instead of find.

        function UpdatePreviewImages() {
          for (var i = 0; i < uploadedFileURLs.length; i++) {
            // get the image like this
            let image = $("#previewImg img");
            image.attr("src", uploadedFileURLs[i])
            let previewImg = $("#previewImg").html();
            let createdImg = $("#previewImageContainer").append(previewImg);
            // No need for this line anymore, because the src is already set
            // $(createdImg).find("img").attr("src", uploadedFileURLs[i]);
           }
         }

I just solved the problem, the main reason is Js is not an OOP language. It doesn't store variables like in OOP languages (I'm using C# 4+ years)

when you try to create a variable and change the source, it will change but it WON'T affect the previewImg variable. Because it doesn't care about the created variable anymore... Briefly, that will fix the problem.

function UpdatePreviewImages() {
            for (var i = 0; i < uploadedFileURLs.length; i++) {
                let previewImg = $($("#previewImg").html()).find("img").attr("src", uploadedFileURLs[i]);
                $("#previewImageContainer").append(previewImg);
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM