1

我的页面出现错误,我相信是因为 php if 语句没有显示条件表。

错误:TypeError:document.getElementById("count2") 为 null 源文件:https ://www.mysite.com/js/clocktimer.js 行:43

我有一个条件语句:

<?php  if ( $this->session->userdata('days_to_challenge') > 0 ) : ?>
    <table id="mytable" border="0">
         <tr>
             <td align="center" colspan="4"><div class="numbers" id="count2" style="padding: 10px; "></div></td>
         </tr>
<?php endif; ?>

我的js代码导致错误:

document.getElementById('count2').style.display="block";
document.getElementById('count2').style.width="390px";
...

挑战的天数已经归零,即。挑战已经开始,所以我没有显示倒计时表。

防止此类错误的最佳方法是什么?

4

3 回答 3

3

在尝试摆弄它之前测试该元素是否存在。

var count2 = document.getElementById('count2');
if (count2) {
    count2.style.display="block";
    count2.style.width="390px";
}
于 2013-03-05T09:03:14.103 回答
0

尝试这个 :

if(document.getElementById('count2')){
   document.getElementById('count2').style.display="block";
   document.getElementById('count2').style.width="390px";
}
于 2013-03-05T09:04:07.133 回答
0

在编写代码之前确保元素存在

if(document.getElementById('count2') != null) {
  document.getElementById('count2').style.display="block";
  document.getElementById('count2').style.width="390px";
}
于 2013-03-05T09:05:07.757 回答