2015-12-11 31 views
-1

現在我使用jQuery來選擇某個元素。如何在沒有特殊子元素的jQuery中獲取元素

CODE:

<form class="form-horizontal" action=""> 
    <div class="form-group"> 
     <input type="text" name="key_word" class="form-control" value=""> 
     <button type="submit" class="btn btn-primary btn-bg-red"> 
      GO 
     </button> 
    </div> 
</form> 

而且我還有其他的形式:

<form class="form-horizontal" action=""> 
    <div class="form-group"> 
     <input type="text" name="key_word" class="form-control" value=""> 
     <input type="text" name="test" class="form-control" value=""> 
     <button type="submit" class="btn btn-primary btn-bg-red"> 
      GO 
     </button> 
    </div> 
</form> 

如何做到的jQuery選擇第一種形式?即如何獲得沒有特殊孩子的元素?

+0

'$('form.form - 水平')。當量(0)'? – roullie

+1

是什麼讓孩子「特別」? –

+0

我猜你的意思是「沒有孩子測試元素」? –

回答

1

您可以使用:not()(或not())和:has()

$('form:not(:has(input[name="test"]))').css('background', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<form class="form-horizontal" action=""> 
 
    <div class="form-group"> 
 
    <input type="text" name="key_word" class="form-control" value=""> 
 
    <button type="submit" class="btn btn-primary btn-bg-red"> 
 
     GO 
 
    </button> 
 
    </div> 
 
</form> 
 
<form class="form-horizontal" action=""> 
 
    <div class="form-group"> 
 
    <input type="text" name="key_word" class="form-control" value=""> 
 
    <input type="text" name="test" class="form-control" value=""> 
 
    <button type="submit" class="btn btn-primary btn-bg-red"> 
 
     GO 
 
    </button> 
 
    </div> 
 
</form>


$('form').not(':has(input[name="test"])').css('background', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<form class="form-horizontal" action=""> 
 
    <div class="form-group"> 
 
    <input type="text" name="key_word" class="form-control" value=""> 
 
    <button type="submit" class="btn btn-primary btn-bg-red"> 
 
     GO 
 
    </button> 
 
    </div> 
 
</form> 
 
<form class="form-horizontal" action=""> 
 
    <div class="form-group"> 
 
    <input type="text" name="key_word" class="form-control" value=""> 
 
    <input type="text" name="test" class="form-control" value=""> 
 
    <button type="submit" class="btn btn-primary btn-bg-red"> 
 
     GO 
 
    </button> 
 
    </div> 
 
</form>

請注意,:has不是CSS,它是一個jQuery的附加。 (還有的是在和小康將它添加到CSS的談話,但它不是在它[但]。)

0

您可以使用以下的選擇:

$("form:not(:has([name='test']))"); 

將只能選擇form元件,其沒有名字爲test的後代。

這裏是working JSFiddle demo。請注意,第二種形式是紅色的,因爲它沒有test項目。

0

,如果你正在尋找不具有輸入元素與「形式制」級(唯一的區別我可以兩種形式之間看到)一個表格,然後

var result = $(".form-horizontal").filter(function(){ 

    return $(this).find('.form-control').size() == 0; 

}); 
相關問題