2012-11-02 113 views
0

我有這個標記:如何選擇包含至少一個[attr = name1]元素的所有元素,該元素又包含至少一個[attr = name2]元素?

<div class="click">click</div> 
<div id="wrapper"> 
<div class="container"> 
<div data-attrfirst='type1'><span data-attrsecond='type2'>must be red</span></div> 
</div> 
</div> 

我想選擇所有.container s表示:
1是#wrapper內;
2.含有data-attrfirst='type1'元素,它依次包含data-attrsecond='type2'元素。
我的要求:
1.我的'#wrapper','type1','type2'值必須保存爲變量。
2.我必須在一些標籤內找到這個(在這種情況下,我選擇body)。

我想這(星號可以被去除,沒有區別):

<script> 
    $(document).ready(function() { 
     $('.click').click(function() { 
      var myid = '#wrapper'; 
      var attrfirst = 'type1'; 
      var attrsecond = 'type2'; 
      var elem = $('*[data-attrfirst=' + attrfirst + ']').has('*[data-attrsecond=' + attrsecond + ']'); 
      $('body').find(myid + ' .container').each(function (i) { 
       if ($(this).has('*[data-attrfirst=' + attrfirst + '] *[data-attrsecond=' + attrsecond + ']')) { 
        $(this).css('color', 'red') 
       } 
      }); 

      $('body').find(myid + ' .container').each(function (i) { 
       if ($(this).has(elem)) { 
        $(this).css('color', 'red') 
       } 
      }); 
      $('body').find(myid + ' .container').filter(function (i) { 
       return $('*[data-attrfirst=' + attrfirst + '] *[data-attrsecond=' + attrsecond + ']', this).length >= 1 
      }).css('color', 'red') 
     }); 
    }); 
</script> 

我在哪裏錯了?而我不明白從Jquery文檔中,.has接受Jquery對象嗎?

+0

很抱歉,但哪裏是你的'.container'在你的HTML標記? –

+0

已保存編輯。我必須再試一次... –

回答

1

你的問題說,要找到#container,所以用這個:

$('body #wrapper .container:has([data-attrfirst="type1"] [data-attrsecond="type2"])'); 

或者,少一點混亂,你可以倒推:

$('[data-attrfirst="type1"] [data-attrsecond="type2"]') 
    .closest('body #wrapper .container'); 

然而,從你的代碼看來,你真的想要找到最後的data-attrsecond="type2"元素。在這種情況下,使用此:

$('body #wrapper .container [data-attrfirst="type1"] [data-attrsecond="type2"]'); 
0

你正在努力尋找.container但你已經定義了「容器」作爲一個id屬性不是一類屬性。 #container應該返回你正在尋找的元素。

+0

當然。編輯完成。 –

0

這將工作:

attrfirst = 'type1'; 
attrsecond = 'type2'; 
thetag = 'body'; 

$(thetag + " #wrapper [data-attrfirst='" + attrfirst + "'] [data-attrsecond='" + attrsecond + "']").css('color', 'red') 
相關問題