用jquery更改图像src

时间:2013-08-26 07:53:46

标签: javascript jquery image attr

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

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

它只改变了最后的图像src但是当我从邻居span获得这些变量值时,它根本不起作用。

我的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>

1 个答案:

答案 0 :(得分: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上。