简体   繁体   中英

Image not loading in HTML when appended by jQuery

Image loads correctly in HTML, but not when appended through jQuery.

The project is set up through webpack and images are loaded through file-loader. The code works correctly when directly typed into HTML however, it doesnt work when I attempt to load it through jQuery.

For HTML :

<img src = {require('../images/icon1.png')} className = 'studentIcon' />

For jQuery :

$("#students").append(
  $("<div class = 'row'>").append(
    $("<div class = 'col-xs-4'>").append(
      "<img src = {require('../images/icon1.png')} />"
    )
  )
)

In HTML the jQuery appended images shows up as:

<img src="{require('../images/icon1.png')}">

with Console error:

icon1.png')%7D:1 GET http://localhost:8080/%7Brequire ('../images/icon1.png')%7D 404 (Not Found)

When directly inserted into HTML the images shows correctly, however I have a large number of images which I want to directly attach to some generated code.

You don't need to "nest" many .append() methods like this.
But what you definitely have to do is to concatenate the string ( + sign) with your templating (which runs first), else it's just characters that are part of the string as is.

Here is what you want:

$("#students").append("<div class = 'col-xs-4'><img src = "+{require('../images/icon1.png')}+" /></div>");

And a more "visual/readable" way for the same:

$("#students")
  .append("<div class = 'col-xs-4'>"+
            "<img src = "+{require('../images/icon1.png')}+" />"+
          "</div>");

Would advise the following.

 $(function() { var students = $("#students"); var row = $("<div>", { class: "row" }).appendTo(students); var col = $("<div>", { class: "col-xs-4" }).appendTo(row); $("<img>", { src: "../images/icon1.png" }).appendTo(col); });
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="students"> </div>

This jQuery creates the various HTML Elements as jQuery OIbjects, appends them as needed, and adds them to the DOM. For the Image Source, it is a relative path to the location on the web server.

Hope that helps.

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