我正在尝试访问元素的style属性以显示表单但是,我收到此错误:未捕获的TypeError:无法读取未定义的属性“样式”。以下示例是一个简化示例。
cookies.php
echo "[a href='test.php?flavor=butter']Bake Butter Cookies[/a]";
echo "[a href='test.php?flavor=chocolate'] Bake Chocolate Cookies [/a]";
>
test.php的
switch($cookieType){
case "chocolate":
echo "<script type='text/javascript'>";
echo "document.chocolate.style.display='block'; ";
echo "</script>";
break;
case "oatmeal-raisin":
echo "<script type='text/javascript'>";
echo "document.oatmealraisin.style.display='block'; ";
echo "</script>";
break;
case "butter":
echo "<script type='text/javascript'>";
echo "document.butter.style.display='block'; ";
echo "</script>";
break;
}
?>
<div id="chocolate" style="display:none;">
<form action="<?php echo $_SERVER['php_self']?>">
<input type="hidden" name="type" value="chocolate"/>
What is your name: <input type="text" name="your_name"/>
How many chocolate chips on each cookie? <input type="text" name="chips"/>
How many many cookies? <input type="text" name="cookies"/>
<input type="submit" name="BAKE!"/>
<input type="reset"/>
</form>
</div>
<div id="oatmealraisin" style="display:none;">
<input type="hidden" name="type" value="oatmealraisin"/>
<form action="<?php echo $_SERVER['php_self']?>">
What is your name: <input type="text" name="your_name"/>
How many raisins on each cookie? <input type="text" name="raisins"/>
How many many cookies? <input type="text" name="cookies"/>
<input type="submit" name="BAKE!"/>
<input type="reset"/>
</form>
</div>
<div id="butter" style="display:none;">
<form action="<?php echo $_SERVER['php_self']?>">
<input type="hidden" name="type" value="butter"/>
What is your name: <input type="text" name="your_name"/>
How many many cookies? <input type="text" name="cookies"/>
<input type="submit" name="BAKE!"/>
<input type="reset"/>
</form>
我之前从未遇到过访问元素的style属性的问题,所以我不确定是什么问题。 switch语句确实有效,因为javascript控制台显示了正确案例的输出。我需要另一双眼睛。有什么建议吗?
答案 0 :(得分:2)
问题不是样式属性,您无法访问元素本身。
您正在尝试访问元素,就好像它们是文档对象中的全局变量一样,只有在怪异模式下的IE中才是如此。您需要使用getElementById方法。替换:
document.chocolate
使用:
document.getElementById('chocolate')
并对应每个元素。