简体   繁体   中英

Image in span tag into an img tag

I try to display an image with <img src="" alt="music cover"> using <span></span> to display the music covers of my web radio.

The link is dynamic, it's why I want to use the span tag for getting the url link of the image's shown during music playback.

I've tried this, but it doesn't work:

<center>
  <p class="current-playlist">
    <span></span>
  </p>
</center>

Here is my code:

    <!DOCTYPE html>
<html>
<center><p class="current-playlist"><img src="<span></span"></p></center>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
             <script>
         var nowPlayingTimeout;
var nowPlaying;

function loadNowPlaying() {
    $.ajax({
        cache: false,
        dataType: "json",
        url: 'https://my_radio_website.com/api/nowplaying_static/radio.json',
        success: function(np) {
            // Do something with the Now Playing data.
            nowPlaying = np;
              $('.current-playlist span').text(np.now_playing.song.art);

            nowPlayingTimeout = setTimeout(loadNowPlaying, 15000);
        }
    }).fail(function() {
        nowPlayingTimeout = setTimeout(loadNowPlaying, 30000);
    });
}

$(function() {
    loadNowPlaying();
});
</script>
</html>

Without the img tag, only the image link is shown, how could I proceed?

<img src="<span></span"> is not a valid HTML, you can not put another element into src tag, you should only set image link to src instead.

To do that, you can crate an <img src=""> element with an empty src attribute.

Then, when you need to load the image you can put the image link into src attribute.

Example:

 const imageLink = "https://picsum.photos/200/300"; // setTimout to simulate ajax request setTimeout(() => { $(".current-playlist img").attr("src", imageLink); // OR document.querySelector('.current-playlist img').src = imageLink; }, 1000);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p class="current-playlist"> <img src=""> </p>

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