代码之家  ›  专栏  ›  技术社区  ›  Arthur Ronald

如何使用jquery检查container div的任何子级是否有错误类?

  •  0
  • Arthur Ronald  · 技术社区  · 15 年前

    假设下面的HTML DIV容器

    <div id="container">
        <form>
            <div>
                <label class="error">Name</label>
                <input type="text" name="name"/>
            </div>
            <div>
                <label>Age</label>
                <input type="text" name="age"/>
            </div> 
        </form>
    </div>
    

    如何使用jquery检查container div的任何子级是否有错误类?

    4 回复  |  直到 15 年前
        1
  •  2
  •   daddywoodland    15 年前
    $("#container .error").length
    
        2
  •  1
  •   Stefan Kendall    15 年前
    $('div').children( function(){
    if( $(this).hasClass( 'error' ) )
    {
    //do something
    }
    } );
    
        3
  •  1
  •   cletus    15 年前
    if ($("#container label.error").length == 0) {
      // none
    } else {
      // at least one
    }
    
        4
  •  0
  •   ranonE    15 年前

    我从集装箱开始:

    代码

    jQuery("#container").find("label").each(function (i) {
      if ( jQuery(this).hasClass("error") ) {
        //error exist
      }
    });