php - 错误 : TypeError: document. getElementById ("count2") 为空,因为条件表。怎么修?

标签 php javascript html web-applications

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

错误:类型错误:document.getElementById("count2") 为空 源文件: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";
...

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

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

最佳答案

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

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

关于php - 错误 : TypeError: document. getElementById ("count2") 为空,因为条件表。怎么修?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15219599/

相关文章:

javascript - 基于另一个数组从对象数组中过滤数组属性

php - 我试图查看我的数据库,但是有错误

php - 在 WooCommerce 中为产品数量添加千位分隔符

javascript发送变量但插入数组php无法正常工作

jQuery 验证插件不适用于单选按钮

html - 使用 css 创建悬停效果

html - 无法使我的网站响应

php - 如何通过php中的忘记密码邮件获取实际密码?

php - GROUP_CONCAT 没有按预期返回输出

javascript - IE6中Jquery Load函数问题