简体   繁体   English

我用javascript生成了html代码(很多div)。 现在我想用GetElementById查找生成的div

[英]I generated html code (lots of divs) with javascript. Now I want to find the generated divs with GetElementById

GetElementById works if I manually added a div id="something" inside the body and use window.onload = init method in the script to get it. 如果我在主体内部手动添加div id =“ something”并在脚本中使用window.onload = init方法来获取它,则GetElementById可以工作。 Works great. 效果很好。

But if I used a for loop to generate divs where id's is 1,2,3 and so on. 但是,如果我使用for循环生成id为1,2,3的div,依此类推。 I can't get it. 我听不懂 Is there a way to get to those generated divs? 有没有办法去那些生成的股利?

This is what generates the html code (just to be clear what I mean): 这就是生成html代码的原因(只是为了清楚我的意思):

for(i=0; i<randomizeColoursList.length; i++)
{
    document.getElementById("renderColors").innerHTML += 
        '<div class=\"box\"><div class=\"' + i + '\"><font color=\"' 
        + randomizeColoursList[i] + '\">' 
        + "" + '<img src=\"dist/card_bg.gif\"></div></div>';                    
}   

Generates one of these: 生成以下之一:

<div class="8"><font color="#3be6c4"><img src="dist/card_bg.gif"></font></div>

Div with class 8 is the id I want to get for example. 例如,类别8的Div是我想要获取的ID。 But is says it's null. 但是据说这是空的。

Thanks. 谢谢。

The id is null because you haven't specified it in your markup creation. idnull,因为您没有在标记创建中指定它。 Looks like you're assigning the id value to class instead. 看来您是将id值分配给class

Generate something more like this: 生成更多类似这样的内容:

<div id="div1" class="8"><font color="#3be6c4"><img src="dist/card_bg.gif"></font></div> 

Also, you don't need to use font tags, nor should you use them. 另外,您不需要使用字体标签,也不需要使用它们。 Just add the styling to the div. 只需将样式添加到div。

<div id="div1" class="8" style="color:#3be6c4;"><img src="dist/card_bg.gif"></div> 

The way you're going about this is a little backwards. 您进行此操作的方式有些倒退。 If you write your code like I have below, then you don't need to give the divs IDs, you end up with an array full of references to them anyway. 如果您像下面那样编写代码,则无需提供div ID,无论如何,最终将得到一个数组,其中包含对它们的引用。

var i, div, img;
var createdDivs = [];
for(i=0; i<randomizeColoursList.length; i++)
{
    div = document.createElement('div');
    img = document.createElement('img');
    div.className = "box";
    div.style.backgroundColor = randomizeColoursList[i];
    div.style.color = randomizeColoursList[i];
    img.src = "dist/card_bg.gif"

    div.appendChild(img);
    document.getElementById("renderColours").appendChild(div);                

    createdDivs.push(div);
}  

Live link: http://jsfiddle.net/7HjLL/ 实时链接: http//jsfiddle.net/7HjLL/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM