Javascript 无法为html中的复选框使用.addClass()方法添加类

Javascript 无法为html中的复选框使用.addClass()方法添加类,javascript,jquery,twitter-bootstrap,class,bootstrap-4,Javascript,Jquery,Twitter Bootstrap,Class,Bootstrap 4,我使用Bootstrap4的表单验证类来实现这个效果 如果提交表单验证失败,我将引导类添加到未验证的元素中(在特定情况下为复选框)。相同的代码在某些情况下可以完美地工作,但在其他情况下却不能。当它不工作时,我注意到如果我console.log(element)元素的无效类,但是如果我检查HTML代码,元素类中没有无效 这是一个代码提取 <?php $random_id = mt_rand( 1000, 9999 ); $gdpr_checkbox_id = "gdpr_checkbox_$

我使用Bootstrap4的表单验证类来实现这个效果

如果提交表单验证失败,我将引导类
添加到未验证的元素中(在特定情况下为复选框)。相同的代码在某些情况下可以完美地工作,但在其他情况下却不能。当它不工作时,我注意到如果我
console.log(element)
元素的
无效
类,但是如果我检查HTML代码,元素类中没有
无效

这是一个代码提取

<?php $random_id = mt_rand( 1000, 9999 ); $gdpr_checkbox_id = "gdpr_checkbox_$random_id"; ?>

<form class="needs-validation" novalidate>
<div class="form-group text-justify px-1">
    <label class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" id="<?=$gdpr_checkbox_id?>" name="gdpr_checkbox" required>
        <span class="custom-control-label font-italic" for="ccwhatsapp_gdpr_checkbox" style="font-size: smaller;">GDPR disclaimer</span>
        <span class="invalid-feedback font-weight-bolder">Invalid feedback</span>
    </label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>

很可能是因为let checkbox为空。函数get\u id\u number看起来像什么更改
\ccwhatsapp\u gdpr\u checkbox(randomId)
\gdpr\u checkbox(randomId)
get\u id\u number()
是我编写的一个函数,用于获取与元素id关联的随机数。复选框不为空,我使用
console.log()
检查,请阅读注释@icolumbro您是否有多个复选框,或者您的问题中给出了正确的表单?@Gulshan这只是一个输入错误,相信我,在原始完整代码中没有语法错误。。。
$( document ).ready( function() {
    $( 'form.needs-validation' ).on( 'submit', function( event ) {
        if ( this.checkValidity() === false ) {
            event.preventDefault();
            event.stopPropagation();

            let checkbox = $( '#ccwhatsapp_gdpr_checkbox_' + get_id_number( $( event.delegateTarget ) ) ); //it's the right checkbox

            console.log(checkbox); //Object { 0: input#gdpr_checkbox_XXXX.custom-control-input, length: 1, [...] }
            checkbox.addClass( 'is-invalid' );
            console.log(checkbox); //Object { 0: input#gdpr_checkbox_XXXX.custom-control-input.is-invalid, length: 1, [...] } but if I inspect HTML there is not is-invalid class...
        }
    } );
} )