2016-11-16 20 views
1

我無法弄清楚如何定位一個跨度類,前提是後面跟有另一個特定類。如果跨度類「markup_zzz」在跨度類「markup_zz」後面加上類別

例如:

<span class="markup_z">Item one</span> 
<span class="markup_zz">Item two</span> 
<span class="markup_xx">Item three</span> 
<span class="markup_zzz">Item four</span> 

我想這樣做,如果markup_zz之後markup_zzz添加類「打開」 markup_zz項目之三在上面的例子中。

將markup_zz視爲父級,將markup_zzz視爲子級。如果有孩子添加對父母開放的課程。

這是我到目前爲止有:

$(document).ready(function() { 
$(".markup_z:not(:last-child):has(+ .markup_zz)") 
.addClass("open"); 
}); 

但是,這僅適用於第一級。

我無法更改跨度,因此必須以其他方式完成。

+1

你是什麼意思「只適用於第一級」?在你的示例中,自markup_xx在markup_zz和markup_zzz之間失敗以後,不會做任何事情? – j08691

+0

在這種情況下,你似乎是錯誤的使用CSS類?這可能會導致你的困難。 – Kzqai

回答

0

我認爲沒有直接的功能/選擇器來實現你所要求的。 您需要搜索 - 針對特定人物旁邊的每個項目 - 如果其類別符合要求。

.nextAll().hasClass()可能是你在找什麼。

這是一個小snipet。點擊跨度來激活每個元素的查找。

$(document).on('click', '.clickable', function() { 
 
     
 
     // get the classes of the span 
 
     var $classes = $(this).attr('class').split(' '); 
 
     var found = false; 
 
     
 
     // foreach class 
 
     for (var i = 0; i < $classes.length && ! found; ++i) { 
 
      var current_class = $classes[i]; 
 
      if (current_class !== 'clickable') { // (avoid checking 'clickable') 
 
       
 
       // add the last letter of the class 
 
       var target_class = current_class + current_class[current_class.length - 1]; 
 
       
 
       // get sibling elements after the clicked one 
 
       var $elems = $(this).nextAll(); 
 
       
 
       // search foreach elem after the clicked one if any of the 
 
       // classes of that element are the target_class 
 
       for (var j = 0; j < $elems.length && ! found; ++j) { 
 
        var elem = $elems[j]; 
 
        if ($(elem).hasClass(target_class)) 
 
         found = true; 
 
       } 
 
      } 
 
     } 
 
     
 
     // if the clicked element matches our requirements 
 
     if (found) { 
 
      /* 
 
      * ... do something 
 
      * 
 
      */ 
 
      $(this).css('background-color', 'green'); 
 
     } 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div style='margin-bottom:50px;'> 
 
    <span class="clickable markup_a">one</span> 
 
    <span class="clickable markup_aa">two</span> 
 
    <span class="clickable markup_bb">three</span> 
 
    <span class="clickable markup_aaa">four</span> 
 
</div>

------------------編輯----------------- -

Execute a function when the document is ready

一旦你知道如何自動執行功能,使用.each()遍歷元素或數組。

看看這個jsFiddle

+0

非常聰明,如果我沒有點擊就可以觸發它,它可能會工作。我一直無法弄清楚,新手和所有,但我一直在使用Google學習! –

+0

謝謝!當我測試它時,它完美地工作,但不在我的代碼中。必須是某種衝突,得到消息停止腳本或調試。現在尋找問題。我猜,令人沮喪但教育。 –

+0

不客氣。如果您需要一些幫助調試,請通過jsFiddle提供您的代碼,我很樂意提供幫助。 – Dacklf