CSS 与 JavaScript - 无法读取属性“未定义”错误
2013-04-08
908
我尝试更改选择列表标题和文本的颜色。我添加了函数
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个回答
您有两个名为“heading”的选择。给它们赋予不同的名称,您的 javascript 将不再抛出错误。
这是一个有效示例: http://jsbin.com/uritid/1/edit
Gordon Tucker
2013-04-08