下面的简单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');
        }
});


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

最佳答案

所有jQuery版本。

if ($('#cta_show_yes:checked').length > 0)
    {
        $('.showCta').show().css('display','table-row');
    } else {
        $('.showCta').hide();
        // $('.showCta').css('display','none'); this is redudant to .hide()
    }


如果该元素不存在,则length将为0。如果length大于0,则该元素存在且is checked

09-26 04:28