2012-02-06 5 views
0

例: 私は以下のHTMLを持っていますが、srcは正規表現を使用しています。それぞれのimgのIDを抽出し、jsonを使用して画像タイトルを取得して属性として返すことはできますが、 。YouTube画像自動タイトルjQuery

<img src="http://i2.ytimg.com/vi/3ZqlS5A9Kjc/hqdefault.jpg"/> 
<img src="http://i2.ytimg.com/vi/GRLtkjLxkiY/hqdefault.jpg"/> 

$('img[src^="http://i2.ytimg.com/vi/"]').each(function(){ // selector and each function 
    var regex = new RegExp(/\/vi\/(.*)\//); //regex variable 
    var imgsrc = $(this).attr("src"); //Individual img's src 
    var id = imgsrc.match(regex)[1]; 
    $.ajax({ 
url: "http://gdata.youtube.com/feeds/api/videos/"+id+"?v=2&alt=jsonc", //using regex extracted id 
dataType: "json", 
success: function (data) {parseresults(data)} 
}); 
function parseresults(result) { 
console.log(result);  
var imgtitle = result.data.title; 
$(this).attr("title", imgtitle); //setting title from extracted id 
} 
}); 
$(document).ready(function() { 
     getYouTubeInfo(); 
}); 

答えて

1

可変範囲が間違っています。 parseresultの "this"はイメージを参照していません。

方法(jsFiddle)これについて:

$('img[src^="http://i2.ytimg.com/vi/"]').each(function() { // selector and each function 
    var regex = new RegExp(/\/vi\/(.*)\//); //regex variable 
    var imgsrc = $(this).attr("src"); //Individual img's src 
    var id = imgsrc.match(regex)[1]; 
    var img = this; 
    $.ajax({ 
     url: "http://gdata.youtube.com/feeds/api/videos/" + id + "?v=2&alt=jsonc", 
     //using regex extracted id 
     dataType: "json", 
     success: function(data) { 
      parseresults(img,data) 
     } 
    }); 

    function parseresults(img,result) { 
     var imgtitle = result.data.title; 
     $(img).attr("title", imgtitle); //setting title from extracted id 
    } 
}); 
関連する問題