【问题标题】:jQuery add image inside of div tagjQuery在div标签内添加图像
【发布时间】:2010-10-30 18:49:18
【问题描述】:

我有一个 div 标签

<div id="theDiv">Where is the image?</div>

我想在 div 中添加一个图片标签

最终结果:

<div id="theDiv"><img id="theImg"  src="theImg.png" />Where is the image?</div>

【问题讨论】:

    标签: jquery


    【解决方案1】:

    您是否尝试过以下方法:

    $('#theDiv').prepend('<img id="theImg" src="theImg.png" />')
    

    【讨论】:

    • 我无法回复上面的 Jose Basilio(没有足够的代表),但 append 会将其放在“图像在哪里?”之后。 Prepend 会放在前面。
    • 我正要支持你使用 prepend,但我注意到你的选择器中缺少“#”...
    • 我用追加的方式开枪了。接得好。 +1
    • appendTo 不起作用...至少在我的代码中,并且在我在 jQuery 文档页面上阅读它之后甚至在发布此线程之前,它都不适合使用。
    • 尝试使用 .append() 和 .html() 添加图片标签,但图片未加载,尽管 标签与源代码正确显示。对此有何建议?
    【解决方案2】:
    $("#theDiv").append("<img id='theImg' src='theImg.png'/>");
    

    您需要阅读文档here

    【讨论】:

      【解决方案3】:

      我的 2 美分:

      $('#theDiv').prepend($('<img>',{id:'theImg',src:'theImg.png'}))
      

      【讨论】:

      • 我喜欢这个关于 $('') 用法的答案,正在寻找它。
      • 也可以在$('
      • 这不是正确答案吗?
      【解决方案4】:

      如果我们想在函数image()被调用时改变&lt;div&gt;标签的内容,我们必须这样做:

      Javascript

      function image() {
          var img = document.createElement("IMG");
          img.src = "/images/img1.gif";
          $('#image').html(img); 
      }
      

      HTML

      <div id="image"></div>
      <div><a href="javascript:image();">First Image</a></div>
      

      【讨论】:

      • 我建议你添加一些解释。
      • 如果我们想改变
        标签的内容,只要调用函数image()。我们必须这样做/ function image() { var img = document.createElement("IMG"); img.src = "/images/img1.gif"; $('#image').html(img); }
      【解决方案5】:

      除了 Manjeet Kumar 的帖子(他没有声明)

      var image = document.createElement("IMG");
      image.alt = "Alt information for image";
      image.setAttribute('class', 'photo');
      image.src="/images/abc.jpg";
      $("#TheDiv").html(image);
      

      【讨论】:

        【解决方案6】:
        var img;
        for (var i = 0; i < jQuery('.MulImage').length; i++) {
                        var imgsrc = jQuery('.MulImage')[i];
                        var CurrentImgSrc = imgsrc.src;
                        img = jQuery('<img class="dynamic" style="width:100%;">');
                        img.attr('src', CurrentImgSrc);
                        jQuery('.YourDivClass').append(img);
        
                    }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-22
          • 1970-01-01
          • 2015-04-28
          • 2012-12-19
          相关资源
          最近更新 更多