通过javascript更改div id

时间:2013-05-16 09:47:48

标签: javascript html

每次按提交时,我都创建了一个简单的页面来更改div id。我的问题是这改变了div_top1 - > div_top2,但第二次按下按钮时,它停止改变:(

<!DOCTYPE html>
<html>
    <head>
        <script>   
            function changediv()
            {                                                    
                document.getElementById("div_top1").innerHTML=Date();          
                document.getElementById("div_top1").setAttribute("id", "div_top2");
                document.getElementById("div_top2").innerHTML="teste";            
                document.getElementById("div_top2").setAttribute("id", "div_top1");
            }
        </script>

        <style>
            .top {               
                background-color: navy;    
                color: white;
                padding: 10px 10px 10px 10px;   
                margin: 5px 5px 5px 5px;                                 
            }

            .down {             
                background-color: aqua;
                padding: 10px 10px 10px 10px;
                margin: 5px 5px 5px 5px;        
            }         
        </style>

    </head>
    <body>
        <div id="div_top1" class="top">This is a paragraph.</div>
        <div class="down"><button type="button" onclick="changediv()">Display Date</button></div>
    </body>
</html> 

3 个答案:

答案 0 :(得分:15)

Working FIDDLE Demo

试试这个:

function changediv()
{   

    if (document.getElementById("div_top1")) {
        document.getElementById("div_top1").innerHTML=Date();          
        document.getElementById("div_top1").setAttribute("id", "div_top2");
    }
    else {
        document.getElementById("div_top2").innerHTML="teste";            
        document.getElementById("div_top2").setAttribute("id", "div_top1");
    }


}

答案 1 :(得分:3)

问题不在于改变身份 - 而是你每次都以两种方式改变它。你需要一个if条件。您还应该使用.id来更改id而不是setAttribute() - 我在过去(很多年前)使用setAttribute进行id更改时遇到了一些浏览器的问题。

DEMO:http://jsfiddle.net/x2nPY/

function changediv() {
    if (document.getElementById("div_top1")) {
        document.getElementById("div_top1").innerHTML = Date();          
        document.getElementById("div_top1").id = "div_top2";
    } else {
        document.getElementById("div_top2").innerHTML = "teste";            
        document.getElementById("div_top2").id = "div_top1";
    }
}

答案 2 :(得分:1)

您可以使用if,例如,如果您想要切换它或在每次提交时更改,如:

function changediv() {                                           
if (document.getElementById("div_top1"))
 {
    document.getElementById("div_top1").innerHTML=Date();          
    document.getElementById("div_top1").setAttribute("id", "div_top2");

 }
 else
 {
    document.getElementById("div_top2").innerHTML="teste";            
    document.getElementById("div_top2").setAttribute("id", "div_top1");
 }

}

请参阅Fiddle Demo