2

以下は私のjavascriptです。

<script type="text/javascript">
document.getElementById('auth').onclick=change;
function change(){
    this.className="account_holder";
}
</script>

htmlは

<td id="auth" class="authorised_reportericon" >
                        <a href="{% url incident.views.authorised_reporter %}">
                        <p align="center" style="color:black;font-size:16px;">Authorised Reporters</p></a>
                    </td>

onclick に td の ID を割り当てましたが、 Uncaught TypeError: Cannot set property 'onclick' of null としてエラーが発生します

4

2 に答える 2

10

次のようdocument.getElementById('auth').onclick=change;に の中に入れます。window.onload

window.onload = function () {
    document.getElementById('auth').onclick=change;
};

あなたが得ているエラーによると、関連する HTML がレンダリングされる前に Javascript が実行されていると思います。つまり、id「auth」を持つ要素が見つかりません。DOM 全体の準備が整ったイベントに配置すると、問題が解決するはずです。

デモ:こちら

于 2013-04-25T19:15:27.800 に答える