jQuery,如果optgroup不包含...

4

我需要帮助处理下面的jQuery代码,它对我来说无法工作。我只想在<optgroup label="Knowledge Base">不存在时触发一些操作。

我的HTML代码(无法更改):

<select id="entry_forum_id" name="entry[forum_id]">
<optgroup label="Knowledge Base"></optgroup>
<optgroup label="Incidents"></optgroup>
<optgroup label="Articles"></optgroup>
</select>

我的jQuery尝试:

if($('optgroup:not([label="Knowledge Base"])')) {
    alert('test');
}

提醒一下,你的选择器是寻找任何没有 label="Knowledge Base" 的 optgroup。 - Barmar
2个回答

6
$('optgroup:not([label="Knowledge Base"])') 返回一个jQuery封装对象,您需要测试它的length属性来检查它是否包含任何元素。您需要进行测试。
if($('optgroup[label="Knowledge Base"]').length == 0) {
    alert('test');
}

5
我认为你不需要使用伪选择器:not。只需检查是否存在具有该标签的optgroup:
if($('optgroup[label="Knowledge Base"]').length == 0) {

点此查看示例代码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接