【问题标题】:jquery - check if parent does not contain element with the classjquery - 检查父级是否不包含该类的元素
【发布时间】:2010-08-12 10:02:44
【问题描述】:

我在尝试找出父元素是否没有具有特定类的元素时遇到问题,如下所示:

//点击表单里面的按钮后——获取父表单的实例

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

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

//做某事

}

任何想法如何实现它 - 因为 has() 似乎没有找到它

【问题讨论】:

    标签: jquery contains


    【解决方案1】:

    .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 也不应该这样使用 - 它只会检查 form 是否具有类,如果它没有。
    • 根据 doco (api.jquery.com/has) 已检查死者。有关更多信息,请参见那里列出的示例。
    猜你喜欢
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2013-09-17
    • 2011-01-10
    相关资源
    最近更新 更多