2012-02-06 3 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

가변 범위가 잘못되었습니다. 구문 분석에서 "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 
    } 
}); 
관련 문제