How to set the image src using jQuery

前端 未结 4 698
半阙折子戏
半阙折子戏 2020-12-29 01:21

I am trying to change the image src attribute using jQuery

jQuery(\"#imageID\").attr(\'src\',\'http://localhost:8080/images/1/myImage.png\' );
相关标签:
4条回答
  • 2020-12-29 02:01

    You need to extract the url part:

    var backgroundImage = $("#imageBlock")
        .css('backgroundImage')
        .replace(/"/g,"")
        .replace(/url\(|\)$/ig, "");
    jQuery("#imageID").attr('src', backgroundImage);
    
    0 讨论(0)
  • 2020-12-29 02:08

    It's because the url() string is wrapped around it. You'll need to strip it from the string, for example using the replace function...

    var bgimg = jQuery("#imageBlock").css('background-image').replace('url(', '');
    bgimg.replace(')', '');
    
    0 讨论(0)
  • 2020-12-29 02:15

    IMO, slice is more appropriate than substring or replace. Try this:

    jQuery("#imageID").attr(
        'src',
        jQuery("#imageBlock").css('background-image').slice(4,-1)
    );
    

    Here, you're slicing the string in between url( and ). See MDC on slice for a detailed description of the method.

    0 讨论(0)
  • 2020-12-29 02:18

    You would need to strip the url( and closing ) parts out for that to work.

    So url(http://localhost:8080/images/1/myImage.png)

    becomes

    http://localhost:8080/images/1/myImage.png

    You could do this with a substring, a regex replace or any method of your choosing.

    http://www.w3schools.com/jsref/jsref_replace.asp

    Perhaps:

    jQuery("#imageID").attr('src',jQuery("#imageBlock").css('background-image').replace('url(','').replace(')','') )

    0 讨论(0)
提交回复
热议问题