0

我正在使用此代码更改图像 src,但它不起作用。如果我为变量文本值写狐狸示例:

track = '212';
artist = 'azealea banks';

它只改变最后一个图像 src 但是当我从邻居跨度获取这个变量值时它根本不起作用。

我的 jQuery 代码:

$(function () {
    $(".plimg").attr("src",

    function (index) {
        var title = $(this).next('span.titletrack').text();
        alert(title);
        var array = title.split(' - ');
        var track = array[0];
        var artist = array[1];

        var output;

        $.ajax({
            url: "http://ws.audioscrobbler.com/2.0/?method=track.search",
            data: {
                track: track,
                artist: artist,
                api_key: "ca86a16ce762065a423e20381ccfcdf0",
                format: "json",
                lang: "en",
                limit: 1
            },
            async: false,
            success: function (data) {
                output = data.results.trackmatches.track.image[0]["#text"];
            }

        });
        return output;
    });
});

和 HTML

<div id="playlist" class="scrollable" style="height: 300px;overflow-y: auto">
    <li>
        <img src="/img/playlist/33a - Sulis Vardo.jpg">
<span class="titletrack">33a - Sulis Vardo</span>
    </li>
    <li>
        <img class="plimg" src="/img/playlist/33a - Shota.jpg">
        <span onclick="playinToplaylist($(this).html());" class="titletrack">33a - Shota</span>
    </li>
</div>
4

1 回答 1

2

我做了一些改变。首先,它只找到最后一张图片,因为只有 HTML 中的最后一张图片具有plimg该类,所以我添加了以下内容:

<div id="playlist" class="scrollable" style="height: 300px;overflow-y: auto">
    <li>
        <img class="plimg"/>
        <span class="titletrack">33a - Sulis Vardo</span>
    </li>
    <li>
        <img class="plimg"/>
        <span onclick="playinToplaylist($(this).html());" class="titletrack">33a - Shota</span>
    </li>
</div>

其次,我更改了 JavaScript 以迭代图像并异步加载图像源。如果您检查对 ajax 调用的响应,则为第二个图像传递的详细信息不会返回任何图像数据,因此这就是未加载该图像的原因。

$(function(){
    $("img.plimg").each(function() {
        var img = $(this);
        var title = img.next("span.titletrack").text();
        var titleDetails = title.split(' - ');
        var track = titleDetails[0];
        var artist = titleDetails[1];

        $.ajax({
            url: "http://ws.audioscrobbler.com/2.0/?method=track.search",
            data: {
                track: track,
                artist: artist,
                api_key: "ca86a16ce762065a423e20381ccfcdf0",
                format: "json",
                lang: "en",
                limit: 1
            },
            async: true,
            success: function (data) {
                var trackData = data.results.trackmatches.track;
                if(!trackData){
                    alert("No track data for " + artist + " / " + track);
                    return;
                }
                var output = trackData.image[0]["#text"];
                img.attr("src", output);
            }
        });            
    });
});

我已将这些更新放在 JSFiddle here上。

于 2013-08-26T08:25:56.393 回答