>  기사  >  웹 프론트엔드  >  document.all과 getElementById, getElementsByName, getElementsByTagName 사용법의 차이점

document.all과 getElementById, getElementsByName, getElementsByTagName 사용법의 차이점

PHP中文网
PHP中文网원래의
2016-05-16 18:57:371045검색

이 문장을 이해하려면 다음을 참조하세요.
예제 1(문서에 어떤 개체가 있는지 이해할 수 있음)

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  <html xmlns="http://www.w3.org/1999/xhtml"> 
  <head> 
  <title>Document.All Example</title> 
  <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /> 
  </head> 
  <body> 
  <h1>Example Heading</h1> 
  <hr /> 
  <p>This is a <em>paragraph</em>. It is only a <em>paragraph.</em></p> 
  <p>Yet another <em>paragraph.</em></p> 
  <p>This final <em>paragraph</em> has <em id="special">special emphasis.</em></p> 
  <hr /> 
  <script type="text/javascript"> 
  <!-- 
  var i,origLength; 
  origLength = document.all.length; 
  document.write(&#39;document.all.length=&#39;+origLength+"[br /]"); 
  for (i = 0; i < origLength; i++) 
  { 
  document.write("document.all["+i+"]="+document.all[i].tagName+"[br /]"); 
  } 
  //--> 
  </script> 
  </body> 
  </html>

출력 결과

Example Heading 
  This is a paragraph. It is only a paragraph. 
  Yet 
another paragraph. 
  This final paragraph has special emphasis. 
  document.all.length=18 
  document.all[0]=! 
  document.all[1]=HTML 
  document.all[2]=HEAD 
  document.all[3]=TITLE 
  document.all[4]=META 
  document.all[5]=BODY 
  document.all[6]=H1 
  document.all[7]=HR 
  document.all[8]=P 
  document.all[9]=EM 
  document.all[10]=EM 
  document.all[11]=P 
  document.all[12]=EM 
  document.all[13]=P 
  document.all[14]=EM 
  document.all[15]=EM 
  document.all[16]=HR 
  document.all[17]=SCRIPT

에 ID, NAME 또는 INDEX 속성을 전달하여 특정 요소에 액세스할 수 있습니다.
예 2(특정 요소에 액세스)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
  "http://www.w3.org/TR/html4/loose.dtd"> 
  <html> 
  <head> 
  <meta http-equiv="Content-Type" content="text/html; 
charset=gb2312"> 
  <title>单击DIV变色</title> 
  <style 
type="text/css"> 
  <!-- 
  #docid{ 
  height:400px; 
  width:400px; 
  background-color:#999;} 
  --> 
  </style> 
  </head> 
  <body><p id="docid" 
name="docname" onClick="bgcolor()"></p> 
  </body> 
  </html> 
  <script language="javascript" 
type="text/javascript"> 
  <!-- 
  function bgcolor(){ 
  document.all[7].style.backgroundColor="#000" 
  } 
  --> 
  </script> 
  上面的这个例子让你了解怎么访问文档中的一个特定元素,比如文档中有一个DIV 
  <p 
id="docid" name="docname"></p>,你可以通过这个DIV的ID,NAME或INDEX属性访问这个DIV: 
  document.all["docid"] 
  document.all["docname"] 
  document.all.item("docid") 
  document.all.item("docname") 
  document.all[7] 
  document.all.tags("p")则返回文档中所有DIV数组,本例中只有一个DIV,所以用document.all.tags("p")[0]就可以访问了。

document.all["element name"].Attribute를 사용할 수 있습니다. name="attribute value" " 요소의 속성을 동적으로 변경합니다. 이 명령문을 사용하면 동적으로 그림 변경, 텍스트 배경 동적으로 변경, 웹 페이지 배경 동적으로 변경, 그림 크기 동적으로 변경, 텍스트 크기 및 색상 동적으로 변경과 같은 다양한 동적 웹 페이지 효과를 만들 수 있습니다.

<script language="JavaScript"> 
function cardClick(cardID){ 
var 
obj; 
for (var i=1;i<7;i++){ 
obj=document.all("card"+i); 
obj.style.backgroundColor="#3A6EA5"; 
obj.style.color="#FFFFFF"; 
} 
obj=document.all("card"+cardID); 
obj.style.backgroundColor="#FFFFFF"; 
obj.style.color="#3A6EA5"; 

for (var i=1;i<7;i++){ 
obj=document.all("content"+i); 
obj.style.display="none"; 
} 
obj=document.all("content"+cardID); 
obj.style.display=""; 
} 
</script>

document.all은 브라우저가 IE인지 확인할 수 있습니다.
if(document.all){
alert("is IE!");
document.all 사용 시 주의 사항
코드 1:

<input name=aaa value=aaa> 
<input id=bbb value=bbb> 
<script language=Jscript> 
alert(document.all.aaa.value) 
//根据name取value 
alert(document.all.bbb.value) //根据id取 value 
</script>
코드 2:

그러나 이름이 동일할 수 있는 경우가 많습니다(예: 확인란을 사용하여 여러 항목을 검색하는 경우). 사용자의 취미)

<input name=aaa value=a1> 
<input name=aaa value=a2> 
<input id=bbb value=bbb> 
<script language=Jscript> 
alert(document.all.aaa(0).value) //显示a1 
alert(document.all.aaa(1).value) 
//显示a2 
alert(document.all.bbb(0).value) //这行代码会失败 
</script>
코드 3: 이론적으로 페이지의 ID는 서로 다릅니다. 서로 다른 태그의 ID가 동일한 경우

document.all.id 就会失败,就象这样: 
<input id=aaa value=a1> 
<input 
id=aaa value=a2> 
<script language=Jscript> 
alert(document.all.aaa.value) //显示 undefined 而不是 a1或者a2 
</script>
코드 4:

복잡한 페이지(코드가 너무 길거나 프로그램에서 자동으로 ID를 생성하는 경우)의 경우
JavaScript 초보자가 작성한 프로그램의 경우 두 태그가 동일한 ID를 가질 가능성이 매우 높습니다.
프로그래밍 시 오류를 방지하려면 다음과 같이 작성하는 것이 좋습니다.

<input id=aaa value=aaa1> 
<input id=aaa value=aaa2> 
<input name=bbb value=bbb> 
<input name=bbb value=bbb2> 
<input id=ccc value=ccc> 
<input name=ddd value=ddd> 
<script language=Jscript> 
alert(document.all("aaa",0).value) 
alert(document.all("aaa",1).value) 
alert(document.all("bbb",0).value) 
alert(document.all("bbb",1).value) 
alert(document.all("ccc",0).value) 
alert(document.all("ddd",0).value) 
</script>
이것이 가장 안전합니다.

다음은 제가 직접 테스트한 것입니다.

 
<html> 
<head> 
<title> 
document.all test 
</title> 
<script language="javascript"> 
function view() 
{ 
/* 
//通过name两种访问格式 
alert(document.all.aaa.value); 
alert(document.all["aaa"].value); 
//通过id的两种访问格式 
alert(document.all.ccc.value); 
alert(document.all["ccc"].value); 
*/ 
//当一页中存在两个name相同的input时不能使用上面的访问方法,因为将返回undefine,请使用下面方式访问 
alert(document.all.aaa(0).value); 
alert(document.all.aaa(1).value); 
//安全的写法 
alert(document.all("aaa",0).value); 
alert(document.all("aaa",1).value); 
} 
</script> 
</head> 
<body> 
<form name="form1" id="f1"> 
<input type="text" name="aaa" > 
<input type="text" name="aaa" id="ccc"> 
<input type="button" name="bbb" value="click" onclick="view();"> 
</form> 
</body> 
</html>
위에서 보면 document.all을 사용할 때 하나의 값을 반환할 수도 있고 여러 값을 반환할 수도 있으므로 길이를 판단한 후 사용해야 하며 그렇지 않으면 오류가 발생한다는 것을 알 수 있다.

다음 질문과 같이, 두 개의 함수가 여러 개의 체크박스를 처리하고 각각 모두 선택 및 모두 선택 취소 기능을 수행하는 경우 다음과 같이 사용하면 어떤 문제가 발생합니까?

 
<HTML> 
<SCRIPT LANGUAGE="JavaScript"> 
<!-- 
function checkall(){ 
var huang = document.all[&#39;huang&#39;]; 
for(i = 0;i < huang.length;i++){ 
if(huang[i].type == "checkbox") 
{ 
huang[i].checked = true; 
} 
} 
} 
function centerall(){ 
var huang = document.all[&#39;huang&#39;]; 
for(i = 0;i < huang.length;i++){ 
huang[i].checked = false; 
} 
} 
//--> 
</SCRIPT> 
<BODY> 
<input type="checkbox" name="huang" value="OFF"> 
<input type="checkbox" name="huang" value="OFF"> 
<input type="checkbox" name="huang" value="OFF"> 
<br> 
<input type="button" value = "checkall" onclick = "checkall();"> 
<input type="button" value = "centerall" onclick = "centerall();"> 
</BODY> 
</HTML>
위 코드를 보면 폼에 체크박스가 여러 개 있을 때는 문제가 없으나, 체크박스가 하나만 있을 때는 문제가 있습니다. 모두 선택하려면 클릭하세요. 확인란이 하나만 있으면 document.all["huang"][0].checked는 더 이상 액세스하는 데 사용되지 않지만 document.all["huang"].checked는 액세스하는 데 사용됩니다. 직접요.

체크박스가 하나만 있는 경우 다음 코드

<HTML> 
<SCRIPT LANGUAGE="JavaScript"> 
<!-- 
function 
checkall(){ 
var huang = document.all[&#39;huang&#39;]; 
if(huang.length){ 
for(i = 0;i < huang.length;i++){ 
if(huang[i].type == "checkbox") 
{ 
huang[i].checked = true; 
} 
} 
}else{ 
huang.checked = 
true; 
} 
} 
function centerall(){ 
if(huang.length){ 
for(i = 
0;i < huang.length;i++){ 
if(huang[i].type == "checkbox") 
{ 
huang[i].checked = false; 
} 
} 
}else{ 
huang.checked = false; 
} 
} 
//--> 
</SCRIPT> 
<BODY> 
<input 
type="checkbox" name="huang" value="OFF"> 
[br] 
<input 
type="button" value = "checkall" onclick = "checkall();"> 
<input 
type="button" value = "centerall" onclick = "centerall();"> 
</BODY> 
</HTML>
로 변경하거나 다른 형식을 사용하여 다음과 같이 getElementsByTagName을 사용하세요.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.