如何检查元素是否有类?已经使用(hasClass方法)?

Shr*_*uti 0 javascript jquery

我有这个HTML或标记.

<fieldset class="ui-dform-fieldset">
    <input type="text" id="totalRetryCount" name="totalRetryCount" tabindex="1" onblur="validateElement('Configuration', 'testSuiteConfigurationform','totalRetryCount')" class="ui-dform-text">
    <legend class="ui-dform-legend">Total Retry Count</legend>
    <label for="totalRetryCount" class="error">Please enter a valid number.</label>
</fieldset>
Run Code Online (Sandbox Code Playgroud)

我想检查标签是否有错误类.我确实喜欢这样

当我调试我的元素值是"totalRetryCount".但它没有显示警报.

element ="totalRetryCount"

if($("#"+element+" "+"label").hasClass('error')){
        alert('-sdafs-')
    }
Run Code Online (Sandbox Code Playgroud)

coo*_*ter 5

你的选择器错了.该totalRetryCountID位于an input,没有孩子.

目标label是兄弟,所以使用next-siblings-selector代替:

if ($("#" + element + " ~ label").hasClass("error")) {
    alert("found error");
}
Run Code Online (Sandbox Code Playgroud)

或这个:

if ($("#" + element + " ~ label.error").length) {
    alert("found error");
}
Run Code Online (Sandbox Code Playgroud)