简体   繁体   中英

Replace img attribute only works first time

So I have this jQuery function:

$('ul li').click(function () {
    var title = $('img', this).attr("title");
    $("a.songtitle span").text(title);

    var artist = $('img', this).attr("artist");
    $("a.songartist span").text(artist);

    var artwork = $('img', this).attr('src');
    artwork = artwork.replace('src');

    $('img.a').attr('src', artwork);
    $(this).addClass('playing').siblings().removeClass('playing');

    audio.load($('a#tunes', this).attr('data-src'));
    audio.play();
});

So, when clicked, it gets album artwork from an img src attribute and replaces it with the current. As you can see in this example , it's only working the first time, and then no longer replaces the img src attribute when you click on "Next". Why is this happening? If someone can help that would be greatly appreciated. Thank you!

This line

$('img.a').attr('src', artwork);

is replacing the src attribute value for all images with class a .

Also, you're missing the second argument to replace() on this line

artwork = artwork.replace('src');

lucky for you, it's not doing anything unless the string "src" appears in the image URL.

If you run your code and then, run this line in your inspector/console:

$('img.a');

You'll see you've changed every image to the exact same source. You should look into giving the item displaying this information a unique ID, so you can start calling it with something like this:

$('#myID img').attr('src',artwork);

I seem to have figured it out. I fixed it by doing:

$('img.a:first').attr('src', artwork);

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