我使用Google圖片搜索API,並在很大程度上覆制了此代碼,該代碼在我的頁面中生成搜索結果。無法在我的img中使用javascript設置標題和alt屬性
for (var i = 0; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var linkContainer = document.createElement('div');
var title = document.createElement('div');
// We use titleNoFormatting so that no HTML tags are left in the title
title.innerHTML = result.titleNoFormatting;
var newImg = document.createElement('img');
newImg.src = result.tbUrl;
newImg.className = 'googleSearchResult';
newImg.title = 'newTitle';
newImg.alt = 'newAlt';
var newLink = document.createElement('a');
newLink.href = "temp_url";
newLink.appendChild(newImg);
contentDiv.appendChild(newLink);
}
在下面的行,
newImg.src = result.tbUrl;
newImg.className = 'googleSearchResult';
newImg.title = 'newTitle';
newImg.alt = 'newAlt';
前兩個,其設置圖像src和類,正常工作,但後兩個,其應設置圖像的標題和alt,根本不工作。任何人都可以看到爲什麼這會發生?謝謝閱讀。
編輯: 下面是當通過Firebug的檢查Firefox中的HTML:
<img alt="" src="http://images.google.com/images?q=tbn:_HZix2CrLSLSOM::bestonlinetvseries.com/deadwood/deadwood_s01.jpg" class="googleSearchResult">
下面是HTML谷歌瀏覽器檢查時
<img alt src="http://images.google.com/images?q=tbn:_HZix2CrLSLSOM::bestonlinetvseries.com/deadwood/deadwood_s01.jpg" class="googleSearchResult">
編輯: 我所試圖做的這裏是在圖像的HTML中存儲額外的一些數據,稍後將用於jQuery插件。如果任何人都可以建議一種替代方法來做到這一點,那也會很好。
我刪除了我的答案,因爲它似乎沒有幫助。實際上,它並不完全正確,因爲DOM圖像元素的確具有屬性「alt」。對不起。 – 2010-07-28 11:31:53
不用擔心,謝謝Felix – ben 2010-07-28 11:35:02
不要在HTML文檔中使用'getAttribute' /'setAttribute'。它比普通屬性訪問方法的可讀性差,並且在IE中很多屬性都是錯誤的。 – bobince 2010-07-28 11:53:21