我想要做的就是在單擊時按ID切換元素的類。JS元素的更改類
<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)">
這將返回一個錯誤......
Uncaught TypeError: Cannot read property 'className' of null
所以我想它不喜歡的條件。
我是JS新手,需要幫助,提前致謝。
[檢查出來(http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript) – jmeas
' document.getElementById(id)'返回null。確保你傳遞了正確的ID到'setLoad' –
另外,將getElementsById的返回值保存在一個var中,你使用很多無用的時間搜索一個元素的dom –