2013-04-08 3 views
1

선택 목록 헤더, 제목 및 텍스트의 색상을 변경하려고했습니다. 이 작업을 수행하려면 changehead(), changetitle()changebody() 함수를 추가했습니다. 그리고 고유 ID를 통해 요소를 바인딩합니다.JavaScript가있는 CSS - 'undefined'속성을 읽을 수 없습니다.

하지만

header = document.form1.heading.options[i].value; 

header = document.form1.heading.options[i].value; 

후 기능 changetitle()에 다음과 같은 오류

Uncaught TypeError: Cannot read property 'undefined' of undefined 기능 changehead()에서

받고 있어요

두 개의 다른 기능을 사용해야하는지 또는 하나의 기능으로 수행해야하는지 확실하지 않습니다.

코드 :

<script> 
    function changehead() { 
     i = document.form1.heading.selectedIndex; 
     header = document.form1.heading.options[i].value; 
     document.getElementById("head1").style.color = header; 
    } 

    function changetitle() { 
     i = document.form1.heading.selectedIndex; 
     header = document.form1.heading.options[i].value; 
     document.getElementById("head2").style.color = header; 
    } 

    function changebody() { 
     i = document.form1.body.selectedIndex; 
     doccolor = document.form1.body.options[i].value; 
     document.getElementById("p1").style.color = doccolor; 
    } 
</script> 
</head> 
<body> 
    <h1 id="head1">Controlling Styles with JavaScript</h1> 
    <hr> 
    <h2 id="head2">Subtitles at this screen. And cery important subtitles!</h2> 

    <hr> 
    <p id="p1">Select the color for paragraphs and headings using the form below. The colors you specified will be dynamically changed in this document. The change occurs as soon as you change the value of either of the drop-down lists in the form.</p> 

    <form name="form1"> <b>Heading color:</b> 

     <select name="heading" onChange="changehead();"> 
      <option value="black">Black</option> 
      <option value="red">Red</option> 
      <option value="blue">Blue</option> 
      <option value="green">Green</option> 
      <option value="yellow">Yellow</option> 
     </select> 
     <br> 
      <B>Body text color:</B> 

     <select name="body" onChange="changebody();"> 
      <option value="black">Black</option> 
      <option value="red">Red</option> 
      <option value="blue">Blue</option> 
      <option value="green">Green</option> 
      <option value="yellow">Yellow</option> 
     </select> 
     <br> <b>Heading second color:</b> 

     <select name="heading" onChange="changetitle();"> 
      <option value="black">Black</option> 
      <option value="red">Red</option> 
      <option value="blue">Blue</option> 
      <option value="green">Green</option> 
      <option value="yellow">Yellow</option> 
     </select> 
    </form> 
</body> 

질문 :

  • 어떻게 오류가있는 상황을 회피하기 위해?
  • &이라는 제목을 바꾸려면 두 가지 다른 기능이 필요합니까, 아니면 하나라도 충분합니까?

답변

1

"머리글"이라는 두 개의 선택 항목이 있습니다. 그들에게 다른 이름을 주면 자바 스크립트가 오류를 던지기를 멈 춥니 다. 여기

은 작업 예입니다 http://jsbin.com/uritid/1/edit 나는이 사용할 수있는 이름

+0

? 저는 Java Script에서 초보자입니다. 두 가지 functoin은 둘 다 사용해야합니다. –

+0

나는이 변경을'header = document.form1.heading1.options [i] .value;'로 시도했다. 그러나 이것은 작동하지 않습니다. –

+0

코드에 따라 작동하는 예제로 업데이트되었습니다. –