在javascript中切换id名称

Ste*_*ard 1 html javascript

使用html和javascript在棋盘上工作.我正在尝试添加一个功能,以便用户可以翻转电路板的视角并遇到我理解的故障,但无法弄清楚如何解决.代码如下....

function flipBoard(){

    document.getElementById("a8").id = "h1";
    document.getElementById("a7").id = "h2";
    document.getElementById("a6").id = "h3";
    document.getElementById("a5").id = "h4";
    document.getElementById("a4").id = "h5";
    document.getElementById("a3").id = "h6";
    document.getElementById("a2").id = "h7";
    document.getElementById("a1").id = "h8";

    document.getElementById("h8").id = "a1";
    document.getElementById("h7").id = "a2";
    document.getElementById("h6").id = "a3";
    document.getElementById("h5").id = "a4";
    document.getElementById("h4").id = "a5";
    document.getElementById("h3").id = "a6";
    document.getElementById("h2").id = "a7";
    document.getElementById("h1").id = "a8";
}
Run Code Online (Sandbox Code Playgroud)

所以....我认为这样可以正常工作,但发现这会对我的电路板造成严重破坏,位于电路板两侧的半白色半黑块.问题当然是在原来的"a1"方块被重命名为"h8"之后,现在有两个"h8"方块,并且在代码的末尾它们都切换回"a1".

我不知道如何同时切换id名称,否则我必须添加一大堆代码,将id名称切换为第三个名称作为占位符,然后再切换到所需的名称.可能,但乏味,我觉得必须有一个更简单的方法来做到这一点.

有任何想法吗?

dc5*_*dc5 5

您可以通过在循环中以编程方式生成id值来减少当前代码的重复:

function flipBoard(){
    var a, h, aVal, hVal, aEl, hEl;

    for(a = 8, h = 1; a > 0; --a, ++h) {
        aVal = 'a' + a;
        hVal = 'h' + h;

        // Store off the current values
        aEl = document.getElementById(aVal);
        hEl = document.getElementById(hVal);

        // swap them
        aEl.id = hVal;
        hEl.id = aVal;
    }
}
Run Code Online (Sandbox Code Playgroud)

演示小提琴