日期:2014-05-16  浏览次数:20368 次

怎样用JS向DIV中添加元素,实现自动索引
我做的一个文本框,在文本框下面加了一个层,想实现自动索引功能

function       showdiv(divname)      
{      
    var   input   =   address_frm.n1.value;
    var   len   =   input.length;
    sug_disp   =   " ";   sug   =   " ";
   
    if   (input.length)   {
        for   (ele   in   countries)//countries是字符串数组,存国家名
        {
            if   (countries[ele].substr(0,len).toLowerCase()   ==   input.toLowerCase())
            {
                sug_disp   =   input   +   countries[ele].substr(len);
                sug   =   countries[ele];
                add();
            }//字符匹配,输入字符,层中显示对应的国家名
        }
    }
    if(input.lenght)
    {
        divname.style.visibility= "visible ";
    }
    else
    {
        divname.style.visibility= "hidden ";
    }
}

function   add(){
div=document.getElementById( 'n2 ');//n2是层名
div.add(sug);//这里不知道怎样添加元素,望高手指点
}


------解决方案--------------------
function add(sug){
var div=document.getElementById( 'n2 ');//n2是层名
var new_div = document.createElement( "DIV ");
new_div.innerHTML = sug;
div.appendChild(new_div);
}
------解决方案--------------------
var a = document.createElement( 'div ');
a.innerHTML =sug;
div.appendChild(a);

移除全部:div.innerHTML = ' ';