JavaScript动态添加/删除div

时间:2012-05-24 16:06:59

标签: javascript dynamic html

我想动态创建多个div。每一个人应该在设定的时间后自行移除。我有创建div和coutdown时间的功能。我不知道如何将它们连接在一起。还有一个问题,如何管理动态添加元素的ID?

function creatediv(e)
{
    ward = document.createElement('div');
    ward.className="dynamic";
    ward.id = id;
    id++;
    ward.style.pixelLeft = mouseX(e);
    ward.style.pixelTop = mouseY(e);
    document.body.appendChild(ward);    
}

function timer(ID, time)
{
    if(time > 0)
    {   
        --time;
        s=time%60;
        m=Math.floor((time%3600)/60);
        var S = document.getElementById(ID);
        S.style.color = "white";
        document.getElementById(ID).innerHTML =((m<10)?"0"+m:m)+":"+((s<10)?"0"+s:s);       
        setTimeout(function () {timer(ID,time)}, 1000);     
    }
    if(time == 0)
    {
        return true;
    }   
}

非常感谢任何提示。 感谢

1 个答案:

答案 0 :(得分:0)

function creatediv(e) {
    ward = document.createElement('div');
    ward.className = "dynamic";
    ward.id = id;
    id++;
    ward.style.pixelLeft = mouseX(e);
    ward.style.pixelTop = mouseY(e);
    document.body.appendChild(ward);
    timer(ward.id, THE_TIME_YOU_WANT);
}

function timer(ID, time) {
    if (time > 0) {
        --time;
        s = time % 60;
        m = Math.floor((time % 3600) / 60);
        var S = document.getElementById(ID);
        S.style.color = "white";
        S.innerHTML = ((m < 10) ? "0" + m : m) + ":" + ((s < 10) ? "0" + s : s);
        setTimeout(function () {
            timer(ID, time)
        }, 1000);
    }
    else {
        // remove the div.
    }
}