2015-12-21 142 views
0

有人可以幫我添加一個鏈接到我通過Javascript添加的圖像嗎?我知道這應該是簡單的,但我不能讓它工作。通過javascript添加鏈接到圖像

jsfiddle

<div class="toggle-panel"> 
Hi there! 
</div> 

var img = new Image(); 
var div = document.querySelector('.toggle-panel'); 
var link = document.createElement('a'); 
link.setAttribute('href', 'www.google.com'); 

img.onload = function() { 
div.appendChild(img); 
}; 

img.src = 'http://findicons.com/files/icons/2603/weezle/256/weezle_sun.png'; 

link.appendChild(img); 
+1

你應該將「div.appendChild(img);」用「div.appendChild(link);」。 –

+0

謝謝,就是這樣! –

+0

$('a')。attr(「href」,「www.google.com」); – Avinash

回答

0

你仍然需要將鏈接添加到div,像這樣:

var img = new Image(); 
var div = document.querySelector('.toggle-panel'); 
var link = document.createElement('a'); 
link.setAttribute('href', 'www.google.com'); 

img.src = 'http://findicons.com/files/icons/2603/weezle/256/weezle_sun.png'; 

link.appendChild(img); 
div.appendChild(link); 

不需要做它的圖像的onload事件。

Fiddle