简体   繁体   中英

How to add html img to page from javascript but not hardcode it in javascript

I use ajaxForm to upload image. On success upload I add uploaded image to div on the page:

$("#ajaxUploadForm").ajaxForm({
            iframe: true,
            dataType: "json",
...
success: function (result) {
$("#imageList").prepend('<img src=' + result.message + '/>');

Now I was thinking that it is not smart to put this hardcoded <img/> tag in javascript code.
What is the best way to put image but not use img tag in prepend() function?

i would not have any problem with that... unless you are worried about invalid url that could break the tag...

you could use simple javascript

var img = new Image();
    img.src = result.message;

$("#imageList").prepend(img);

IMHO that is the best way, there's no need to change anything. If you don't want to dynamically append/detach, you could have an existing img as a placeholder and just change its src attribute when you wanted to change it:

<img id="placeholder" src="initial/path" />

$("#placeholder").attr("src", result.message);

But since you're dealing with an image list, as your code suggested, I think your original solution is more appropriate for your case. If you ever decide to remove an image or sort the list or whatever, you can selected them using $("imageList img") .

Edit: OTOH if you have a very complex structure, that you want to code in HTML but also need to make dynamic copies of it, you can use clone as an alternative:

<div id="model" style="display:none">complex markup goes here</div>

$("#model").clone().attr("id",anotherID).appendTo(target).show();

Use a template. For instance:

<div style="display:none">
  <!-- This div contains all your templates -->
  <img src="about:blank" class="classesYouNeed" id="uploadSuccess">
</div>

and then use javascript:

$("#ajaxUploadForm").ajaxForm({
  iframe: true,
  dataType: "json",
  ...
  success: function (result) {
    var img = $('#uploadSuccess')
      .clone()
      .attr('id', somethingElse)
      .attr('src', result.message)

    $("#imageList").prepend(img);
  })
})

There are jQuery templating frameworks out there that will make this much easier.

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