使用JavaScript的CSS - 无法读取属性“未定义”错误

时间:2013-04-08 22:20:29

标签: javascript

我尝试更改选择列表标题,标题和文字的颜色。我添加了函数changehead()changetitle()changebody()来执行此操作。并通过唯一ID绑定元素。

但我收到以下错误

  

Uncaught TypeError: Cannot read property 'undefined' of undefined

之后的函数changehead()中的

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

并在

之后的函数changetitle()
header = document.form1.heading.options[i].value;

我不确定是否应该使用两种不同的功能,或者是否可以使用一种功能。

代码:

<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 个答案:

答案 0 :(得分:1)

您有两个名为“heading”的选项。给他们不同的名字,你的JavaScript将停止抛出错误。

以下是一个工作示例:http://jsbin.com/uritid/1/edit