即使ID不在页面上,检查是否选中复选框也是如此

时间:2015-01-29 18:01:44

标签: php jquery

全部, 我有以下代码:

if($('#future_date_post:checked')){
    alert('it is open');
    $('#future_date_post_select').show();
}

然后我在页面上有以下PHP代码:

if($action=="edit" && $post_to_edit['post_status'] == "future"){
    echo '<input type="checkbox" id="future_date_post" name="future_date_post" value="yes" checked> Click this box to schedule this post for a future date<br>';
}else{
    echo '<input type="checkbox" id="future_date_post" name="future_date_post" value="yes"> Click this box to schedule this post for a future date<br>';
}

我的jQuery总是说我的复选框有一个选中的值,即使它没有99%的时间。即使其他页面上没有ID,我也会在每个页面上收到提醒。为什么这样做?

2 个答案:

答案 0 :(得分:2)

您的if声明不正确。 jQuery选择将始终返回一个jQuery对象(尽管长度为零),即使页面上没有匹配的选择器。在JavaScript中,除truenullundefinedNaN""外,所有对象的评估均为0

因为零是&#34;假的&#34;在javascript中,只需检查返回对象的长度:

if($('#future_date_post:checked').length){
    alert('it is open');
    $('#future_date_post_select').show();
}

答案 1 :(得分:2)

several ways来做。要得到一个布尔值,我会检查它:

if($('#future_date_post').is(':checked')){
    alert('it is open');
    $('#future_date_post_select').show();
}