1

我试图更改选择列表标题、标题和文本的颜色。我添加了功能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>

问题:

  • 如何规避出现错误的情况?
  • 是否需要两种不同的功能来更改头部和标题,或者一个就足够了(如果是 - 如何)?
4

1 回答 1

1

您有两个名为“标题”的选择。给他们不同的名字,你的 javascript 将停止抛出错误。

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

于 2013-04-08T22:26:52.920 回答