【问题标题】:jQuery get the image srcjQuery获取图片src
【发布时间】:2013-11-25 01:45:34
【问题描述】:

我希望当我点击按钮时,我可以得到具体的img src,并在div类img-block块中显示img src。

HTML

<button class="button">Click</button>
<div class="img1">
    <img src="img.jpg" alt="">
</div>

<div class="img-block"></div>

CSS

.img-block{
    position: absolute;
    top:10%;
    right:10%;
    background-color: red;
    width: 500px;
    height: 500px;
}
.img1 img{
    width: 200px;
}

JS

$('.button').click(function(){
  var images = $('.img1 img').attr(src);
  alert(images);      
});

但现在我面临的问题是获取img src。
所以我用alert来做测试,结果是什么都没有提醒。

【问题讨论】:

    标签: jquery


    【解决方案1】:

    src 应该用引号引起来:

    $('.img1 img').attr('src');
    

    【讨论】:

      【解决方案2】:

      完整的网址使用

      $('#imageContainerId').prop('src')
      

      用于相对图像 url 使用

      $('#imageContainerId').attr('src')
      

      function showImgUrl(){
        console.log('for full image url ' + $('#imageId').prop('src') );
        console.log('for relative image url ' + $('#imageId').attr('src'));
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <img id='imageId' src='images/image1.jpg' height='50px' width='50px'/>
      
      <input type='button' onclick='showImgUrl()' value='click to see the url of the img' />

      【讨论】:

        【解决方案3】:

        你可能会发现 likr

        $('.class').find('tag').attr('src');
        

        【讨论】:

          【解决方案4】:

          在处理 HTML DOM(即this)时,必须使用数组选择器[0] 从 Javascript 数组中检索 jQuery 元素。

          $(this)[0].getAttribute('src');
          

          【讨论】:

            【解决方案5】:

            这是你需要的

             $('img').context.currentSrc
            

            【讨论】:

              【解决方案6】:

              在我的例子中,这种格式适用于最新版本的 jQuery:

              $('img#post_image_preview').src;
              

              【讨论】:

                【解决方案7】:

                html:

                <img id="img_path_" width="24" height="24" src=".." class="img-fluid" alt=“">
                

                js:

                $('#img_path_').attr('src')
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-10-20
                  • 2013-02-10
                  • 1970-01-01
                  • 2011-02-24
                  • 2021-08-12
                  相关资源
                  最近更新 更多