简体   繁体   English

替换img属性仅在第一次使用时有效

[英]Replace img attribute only works first time

So I have this jQuery function: 所以我有这个jQuery函数:

$('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. 因此,当单击该按钮时,它将从img src属性获取专辑插图,并将其替换为当前。 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". 如您在本示例中看到的那样,它仅在第一次工作,然后在您单击“下一步”时不再替换img src属性。 Why is this happening? 为什么会这样呢? If someone can help that would be greatly appreciated. 如果有人可以提供帮助,将不胜感激。 Thank you! 谢谢!

This line 这条线

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

is replacing the src attribute value for all images with class a . 正在使用类a替换所有图像的src属性值。

Also, you're missing the second argument to replace() on this line 另外,您在此行上缺少第二个参数replace()

artwork = artwork.replace('src'); 艺术作品= Artwork.replace('src');

lucky for you, it's not doing anything unless the string "src" appears in the image URL. 对您来说很幸运,除非图像URL中出现字符串“ src”,否则它什么也不做。

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: 您应该考虑给显示此信息的项目一个唯一的ID,以便您可以使用类似以下的代码来调用它:

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

I seem to have figured it out. 我似乎已经知道了。 I fixed it by doing: 我通过以下方法解决了它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM