2016-03-26 200 views
0

這是成功顯示圖像的完整url。如何將JSON圖像值分配給HTML img標記

http://openweathermap.org/img/w/04d.png

注意,除了JSON屬性「圖標」規定值「04D」,它是由我來把那爲URL才能使用它。

只是作爲參考,以表明JSON路徑是正確的,這裏是如何我順利地從顯示的圖像存儲在同一個JSON屬性的文本。

的document.getElementById(「weatherDescriptionData」 ).innerHTML = data.weather [0] .description;

這是HTML img標籤

<img src="" id="weatherIconData"></div> 

這是我沒能成功,顯示圖像的第一個方法。 (向右滾動)

document.getElementById("weatherIconData").src = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png"; 

這是我嘗試顯示圖像失敗的第二種方法。

$("#weatherIconData").prop('src', "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png"); 

我查了一下,發現

console.log(data.weather[0].icon); 

確實事實上回報04D。

如何在HTML視圖中顯示JSON中提供的圖像?

+0

@PencilCreate我編輯[@ user6101582的答案](http://stackoverflow.com/a/36236176/227299)添加一些更多的細節。被接受的答案可能有效,但它不是正確的解決方案,因爲它解決了一個並沒有真正理解的問題。沒有理由爲什麼應該在$ document.getElementById('id')' –

回答

2

嘗試jQuery的.attr

$("#weatherIconData").attr('src', 'http://openweathermap.org/img/w/' + data.weather[0].icon + '.png'); 

html標記,也開始爲<img>但關閉與</div>關閉這個與<img id="" src="" />

$(function() { 
 
    var data = { 
 
    weather: [{ 
 
     icon: '04d' 
 
    }] 
 
    }; 
 
    
 
    $("#weatherIconData").attr('src', 'http://openweathermap.org/img/w/' + data.weather[0].icon + '.png'); 
 
});
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<script src="https://code.jquery.com/jquery-2.1.4.js"></script> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width"> 
 
    <title>JS Bin</title> 
 
</head> 
 
<body> 
 
<img src="" id="weatherIconData"/> 
 
</body> 
 
</html>

+0

attr上使用'$('#id')',謝謝 – PencilCrate

+0

我通常不會冷靜地回答工作問題,但是這是一個瘋狂的嘗試,運氣不好,正確關閉'img'標籤會做伎倆 –

2

你沒有關閉<img />標籤。

<img id="weatherIconData" /> 

jQuery可能已經解決了這個問題,但不是@ user2950720建議的正確解決方案。沒有理由爲什麼$('#id')應使用在document.getElementById('id')

var data = { 
 
    weather: [{ 
 
    icon: '04d' 
 
    }] 
 
}; 
 

 
document.getElementById("weatherIconData").src = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";;
<img src="" id="weatherIconData">

-1

使用attr超過propWorking Fiddle

$("#weatherIconData").attr('src', "...."); 
+0

是的!共同先生downvoter。解釋我的錯誤。做一個男人 –

+0

我還能得到多少? –

+1

我upvoted。你提供了正確的答案,即使user2950720首先提供了它。謝謝。 – PencilCrate

相關問題