jQuery - 检查父元素是否不包含具有类名的元素

3
我在尝试查找父元素是否没有特定类名的子元素时遇到了问题,代码如下:

// 点击表单内按钮后获取父表单实例

var par = $(this).parent('form');

if(!par.has('warn')) {

// 进行某些操作

}

请问如何实现这个功能?因为has()方法好像无法找到它。
1个回答

3

.has并不返回布尔值,因此如果没有匹配项,则返回的对象将有0个成员。

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
    <form>
        <div><input id="thebutton" type="button" value="Click Me" /></div>
        <div class="test">test div</div>
    </form>
<script>

$(document).ready(function() {
    $('#thebutton').click(function() {
        var par = $(this).parent('form');
        if(par.has('.warn').length === 0) {
            // do something
            alert('nothing');
        }
    });
});

</script>

</body>
</html>

你说得没错,但是has也不应该这样使用——它只会检查表单是否有这个类,并在没有时从集合中删除它。 - Kobi
根据文档(http://api.jquery.com/has/),has()函数检查后代元素。请查看文档中列出的示例以了解更多信息。 - Jonathan

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