javascript将图像分配给alt文本

时间:2015-06-15 13:05:49

标签: javascript

我使用javascript

我没有找到如何将图像分配到span并为此图像添加alt文本

我有这段代码:

<a href="testUrl" >
  <span id="101"></span>                                    
</a>

这是代码javascript:

var pic = "C:\image1.jpeg"; 
var img = new Image(); 
img.src=pic ;
var defautValue='10'
var nbrInc='(';
nbrInc=nbrInc.concat(defautValue,img,')');  
document.getElementById("101").innerHTML=nbrInc;

2 个答案:

答案 0 :(得分:0)

EXAMPLE

var elem = document.createElement("img");
elem.setAttribute("src", "http://img.zohostatic.com/discussions/v1/images/defaultPhoto.png");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("101").appendChild(elem);

答案 1 :(得分:0)

jsfiddle示例:https://jsfiddle.net/dxbv69uq/

var pic = "http://images.visitcanberra.com.au/images/canberra_hero_image.jpg"; 
var img = new Image();
img.onload = function() {
    var e = document.createElement("img");
    e.setAttribute("src", img.src);
    e.setAttribute("alt", "title");
    document.getElementById("101").appendChild(e);
}
img.src=pic;