我试图访问元素的样式属性以显示表单,但是我收到此错误:Uncaught TypeError: Cannot read property 'style' of undefined。下面的例子是一个简化的例子。
cookies.php
echo "[a href='test.php?flavor=butter']Bake Butter Cookies[/a]";
echo "[a href='test.php?flavor=chocolate'] Bake Chocolate Cookies [/a]";
?>
测试.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>
我以前在访问元素的样式属性时从未遇到过问题,所以我不确定是什么问题。 switch 语句确实有效,因为 javascript 控制台显示正确情况的输出。我需要另一双眼睛。有什么建议吗?
最佳答案
问题不是样式属性,您无法访问元素本身。
您正在尝试访问元素,就好像它们是文档对象中的全局变量一样,这仅在 IE 中的怪异模式下才是正确的。您需要使用 getElementById 方法。替换:
document.chocolate
与:
document.getElementById('chocolate')
和每个元素对应。
关于php - 使用 javascript 访问元素样式属性时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3287021/