2

次のコードがFirefoxとChromeで正常に実行されるのに、IE6とIE8でエラーが発生するのはなぜですか?

<!DOCTYPE html>
<html>  
<head></head>  
<body>
<div id="abc"></div>
<script type="text/javascript">
var doLoad = function() {
  // error in ie6 and ie8
  abc = document.getElementById("abc"); 
  abc.innerHTML = "hello world!"; 
  // correct in ie6 and ie8
  /*
  var abc = document.getElementById("abc"); 
  abc.innerHTML = "hello world!";
  */
  // correct in ie6 and ie8
  /* 
  xyz = document.getElementById("abc"); 
  xyz.innerHTML = "hello world!";
  */
}
window.onload = doLoad;
</script>  
</body>  
</html>

varしかし、前に追加するdocument.getElementById("abc");か、名前abcを変更するxyzと、IE6とIE8でうまく動作します。

4

2 に答える 2

4

IE creates a global JavaScript variable for each element with an ID. These variables cannot be overridden afaik and cause all sorts of problems.

The thing to keep in mind: Don't create global variables with the same name as element IDs. Don't create global variables at all.

于 2012-04-15T11:35:48.143 に答える
3

var ステートメントを見逃すと、変数が window オブジェクトに代入されます。だからそれは同じですwindow.abc = document.getElementById('abc');

しかし、window.abc はまさに id abc の div であり、IE ではそれに値を割り当てることはできません。

于 2012-04-15T11:35:59.953 に答える