在JS中交换id - 这只能工作一次.为什么?

fst*_*ero 3 javascript css dom

我正在玩点击事件,我注意到这个功能只是第一次使用.这是为什么?我怎样才能使它能够在两个元素之间不断交换id?

并且,如果要在大量元素中传递id,那么方法会有戏剧性的变化吗?

我根本不使用jQuery.谢谢.

 window.onload = function() {
	document.addEventListener('click', function(e) {
	  document.getElementById("purpleSquare").id = 'redSquare';
	  document.getElementById("redSquare").id ="purpleSquare";
	})
};
Run Code Online (Sandbox Code Playgroud)
#redSquare {
	background-color: red;
    width: 20px;
    height: 20px;
}
#purpleSquare {
	background-color: purple;
    width: 20px;
    height: 20px;
}
Run Code Online (Sandbox Code Playgroud)
        <div id="redSquare"></div>

        <div id="purpleSquare"></div>
Run Code Online (Sandbox Code Playgroud)

Ori*_*iol 5

因为在运行此代码后......

document.getElementById("purpleSquare").id = 'redSquare';
Run Code Online (Sandbox Code Playgroud)

......会有两个元素id="redSquare".

因此,这将是不可靠的:

document.getElementById("redSquare")
Run Code Online (Sandbox Code Playgroud)

DOM2DOM3中,行为未定义:

如果有多个元素,则不定义行为ID.

DOM4中,将返回第一个元素.因此,第一次单击它将起作用,因为您想获得第一个.但是当你再次点击时,你想获得第二个,所以它不起作用.

相反,您可以在更改其ID之前将元素存储在变量中.

var el1 = document.getElementById("purpleSquare"),
    el2 = document.getElementById("redSquare");
el1.id = 'redSquare';
el2.id ="purpleSquare";
Run Code Online (Sandbox Code Playgroud)

document.addEventListener('click', function(e) {
  var el1 = document.getElementById("purpleSquare"),
      el2 = document.getElementById("redSquare");
  el1.id = 'redSquare';
  el2.id ="purpleSquare";
})
Run Code Online (Sandbox Code Playgroud)
#redSquare {
  background-color: red;
  width: 20px;
  height: 20px;
}
#purpleSquare {
  background-color: purple;
  width: 20px;
  height: 20px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="redSquare"></div>
<div id="purpleSquare"></div>
Run Code Online (Sandbox Code Playgroud)