2011-08-03 65 views
2

我遇到了jQuery查詢問題。構建jQuery查詢需要幫助

考慮以下(瘋了)HTML例子:

<!-- this is the outermost condition --> 
<div id="condition"> 

    <!-- this is a tag that I am looking for --> 
    <input type="text" /> 

    <div id="condition"> 
      <input type="radio" /> 
    </div> 

    <div> 

      <div id="condition"> 
       <input type="checkbox" /> 
      </div> 

      <!-- this is a tag that I am looking for --> 
      <input type="text" /> 

    </div> 
</div> 

鑑於上面的例子中,標記和最外側的條件(在上面看到的),我怎麼能得到所有輸入單元內的情況下,那也不是內在條件的成員?

我已經提供了示例,以便您可以查看哪些標記我希望查詢返回。

+4

在單個頁面上有重複的id是無效的HTML。考慮使用類來代替。 –

+0

你嘗試過什麼嗎? –

回答

1

頁面上的所有html元素都應該有唯一的ID。

這就是說,你可以做這樣的事情:

// select the :first #condition 
var $first = $("#condition:first"); 

// use map() to filter out inputs that don't meet our criteria 
// and dump them into the inputs Array. 
var inputs = $first.find("input").map(function() { 

    // select parent with #condition ID 
    var $parent = $(this).parent("#condition"); 

    // if parent == null or parent doesn't have any parents with ID = #condition 
    // return the input, otherwise null, which removes it from the list 
    return $parent.length == 0 || $parent.parents("#condition").length == 0 
     ? $(this) : null; 
}); 

你最終是輸入的Array未包裹在#condition或其父是第一#condition元素


工作示例:http://jsfiddle.net/hunter/EsYLx/

0

你可以這樣做:

var found = $('#condition input').filter(function() { 
    var parents = $(this).parents('.condition'); 
    return parents.length === 1 && parents[0].id === 'condition'; 
}); 

但是,你的HTML不僅是瘋了,這是無效的。你不能有多個具有相同ID的元素,所以你需要先解決這個問題。

這裏有一個工作示例:http://jsfiddle.net/FishBasketGordo/R7MX4/

0

好第一關,你不能有2個元素具有相同的ID - 它們必須是唯一的,但如果你繼續和他們改爲你可以使用類似的類:

$('#condition input:not(#condition #condition input)').doSomething(); 
0

This應該工作:注意你有2個ID和ID應該是唯一的。

$("#condition > input").html(); 
+0

這就是我一開始以爲的想法,但是如果你看看OP的例子,他們想要包含一個輸入,它是一個外部條件的孩子。 – FishBasketGordo

+0

我想我明白了。顯然,如果ID不一樣但它可能非常相似,這會更容易。 – hunter