如何处理JavaScript当它正在寻找的Div缺失时无法读取属性错误?

Jas*_*vis 0 javascript jquery

下面这个简单的JS/jQuery代码在没有带有该ID的项目的页面上导致此错误...

Uncaught TypeError: Cannot read property 'checked' of null

jQuery(document).ready(function($) {

        //Show or Hide Footer Call To Action Settings Metab Box
        if (document.getElementById('cta_show_yes').checked) {
            $('.showCta').show();
            $('.showCta').css('display','table-row');
        } else {
            $('.showCta').hide();
            $('.showCta').css('display','none');
        }
});
Run Code Online (Sandbox Code Playgroud)

当页面缺少ID为cta_show_yes的项目时,如何确保不会出现此错误?

Que*_*tin 5

在尝试访问该属性之前,请测试是否获得(非)null值.

var element = document.getElementById('cta_show_yes');
if (element && element.checked) {
Run Code Online (Sandbox Code Playgroud)