How to create a new img tag with JQuery, with the src and id from a JavaScript object?

后端 未结 4 1067
眼角桃花
眼角桃花 2020-12-02 14:01

I understand JQuery in the basic sense but am definitely new to it, and suspect this is very easy.

I\'ve got my image src and id in a JSON response (converted to an

相关标签:
4条回答
  • 2020-12-02 14:30
    var img = $('<img />', { 
      id: 'Myid',
      src: 'MySrc.gif',
      alt: 'MyAlt'
    });
    img.appendTo($('#YourDiv'));
    
    0 讨论(0)
  • 2020-12-02 14:33

    You save some bytes by avoiding the .attr altogether by passing the properties to the jQuery constructor:

    var img = $('<img />',
                 { id: 'Myid',
                   src: 'MySrc.gif', 
                   width: 300
                 })
                  .appendTo($('#YourDiv'));
    
    0 讨论(0)
  • 2020-12-02 14:40

    For those who need the same feature in IE 8, this is how I solved the problem:

      var myImage = $('<img/>');
    
                   myImage.attr('width', 300);
                   myImage.attr('height', 300);
                   myImage.attr('class', "groupMediaPhoto");
                   myImage.attr('src', photoUrl);
    

    I could not force IE8 to use object in constructor.

    0 讨论(0)
  • 2020-12-02 14:49

    In jQuery, a new element can be created by passing a HTML string to the constructor, as shown below:

    var img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img'))
    img.attr('src', responseObject.imgurl);
    img.appendTo('#imagediv');
    
    0 讨论(0)
提交回复
热议问题