如何添加一个ID到一个图像只使用javascript

问题描述:

基本上我试图给我的形象一个ID ...但我不知道如果这是可能的不使用HTML ...如果你感到困惑看看我的代码如何添加一个ID到一个图像只使用javascript

function add_conner_6th() { 
    var src = "src"; 
    show_image("src", 300,415, "Conner 6th"); 
} 

function show_image(src, width, height, alt) { 
    var img = document.createElement("src"); 
    img.src = src; 
    img.width = width; 
    img.height = height; 
    img.alt = alt; 
    document.body.appendChild(img); 
} 

我试过添加img.id =“名称”,但它只是不起作用。我DESPERATE

+0

你尝试'img.id = “名称”;'用分号? – tjons

+0

尝试创建一个图像,而不是'src'元素? – adeneo

+0

@TJonS是的。但是当图像出现时,我使用document.getElementById,然后它不会找到它的图像...但是当我在html中创建图像并使用相同的id时,它删除了图像 – user3367007

img.id = "name"应该工作,但我相信问题是,你有createElement("src")。这应该是createElement("img"),例如:

function show_image(src, width, height, alt) { 
    var img = 
     document.createElement("img"); 
    img.src = src; 
    img.width = width; 
    img.height = height; 
    img.alt = alt; 
    img.id = "name"; 
    document.body.appendChild(img); 
} 

Demonstration