我試圖使用從JSON調用獲得的值動態添加標題到許多圖像。Jquery添加標題屬性與來自JSON調用的數據
這是我迄今爲止
$(".watch_view img").each(function() {
$.ajax({
url: 'http://gdata.youtube.com/feeds/api/videos/T2aMBeeM4yw?v=2&alt=jsonc',
dataType: 'json',
success: function(json) {
song_title = json.data.title;// song title is retrieved without issue
}
});
alert(song_title); //this to be removed
//the title attr below is only added when the above alert is in place
$(this).attr('title', song_title);
$(this).attr('alt', "This works everytime");
});
現在上述作品,但只有當我通過添加不必要的警告「停止」的過程 - 我只能猜測,代碼在它從JSON調用(?)中檢索數據之前正在執行,並且警報使其能夠趕上。
我想我需要另一個函數,在JSON調用之後執行,或者讓代碼進入'成功'函數,但我不確定如果在這種情況下如何保留'this'元素。
幫助和建議非常感謝。
感謝
克里斯
SUCCESSS是溫控功能!你有沒有試過在成功中使用$(this)。 AFAIR它不應該是一個問題 –
它不會在成功內部拋出一個錯誤(不管它是什麼),但它不會添加標題attr。該位置的警報顯示檢索到正確的數據。 – Chris