【发布时间】:2013-05-18 21:09:03
【问题描述】:
我要做的就是在点击元素时按 ID 切换元素的类。
<script>
function selectLoad(id)
{
if(document.getElementById(id).className == "load") {
document.getElementById(id).className = "loadSelected";
} else {
document.getElementById(id).className = "load";
}
}
</script>
<div class="load" id=" ... set by PHP per element ... " onclick="selectLoad(this)">
这会返回一个错误...
未捕获的类型错误:无法读取 null 的属性“className”
所以我猜它不喜欢有条件的。
我是 JS 新手,需要帮助,在此先感谢。
【问题讨论】:
-
document.getElementById(id)返回空值。确保您将正确的 id 传递给setLoad -
另外,将getElementsById的返回值保存在一个var中,你会浪费很多时间在dom中搜索一个元素
-
我猜“selectLoad(this)”可能会给你带来麻烦。使用 php 更容易设置 id:'"selectLoad(\''.php_var.'\');"
标签: javascript