2017-07-10 9 views
0

各a.parent_linkからテキストを取得し、対応する各トグルボタン(button.sub-expand_collapse)にaria-labelとして適用したいと考えています。私が望む最終的な結果は、aria-expanded = trueにaria-label = close +(text)を追加し、aria-expanded = falseにaria-label = expand +(text)を追加する場合です。それぞれのテキストを取得してaria-labelに使用する

最初の部分は私にテキスト

$(".togSubList").each(function() { 
     var bob = $(this).find(".parent_link").text(); 
     console.log(bob); 
    }); 

を与えるしかし、私はアリア・ラベルを追加するには、各1を得ることができません。

 $(".togSubList").each(function() { 
     var bob = $(this).find(".parent_link").text(); 
     //console.log(bob); 
     $(".sub-expand_collapse").each(function(){ 
      $(this).attr("aria-label","expand " + bob) 
     }); 
    }); 

HTML

<li class="sub_p01 togSubList"> 

     <button class="sub-expand_collapse" aria-expanded="false"> 
      <i class="fa fa-plus" aria-hidden="true"></i> 
     </button> 

     <a id="subLnk_01" class="parent_link menu_p01" href="m01_c01_p01.html"><strong>Space saving widgets</strong></a> 
     <ul aria-labelledby="subLnk_01" class="sub_items"> 
      list of links 
     </ul> 
    </li> 
+0

あなたのコードは私のテストで動作します:https://jsfiddle.net/8xgtcg87/ たぶんjQueryのロードエラーがどこかにありますか? –

答えて

1

だけnode traverseを使用して内部LIが一つだけの要素を持っているので、あなたは、第二の各機能を必要としないでください。このような要素はfindです。 attributeを適用します。

$(".togSubList").each(function() { 
 
     var bob = $(this).find(".parent_link").text(); 
 

 
     $(this).find(".sub-expand_collapse[aria-expanded='false']").attr("aria-label","expand " + bob); 
 
     $(this).find(".sub-expand_collapse[aria-expanded='true']").attr("aria-label","close " + bob); 
 
      
 

 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<li class="sub_p01 togSubList"> 
 

 
     <button class="sub-expand_collapse" aria-expanded="false"> 
 
      <i class="fa fa-plus" aria-hidden="true"></i> 
 
     </button> 
 

 
     <a id="subLnk_01" class="parent_link menu_p01" href="m01_c01_p01.html"><strong>Space saving widgets</strong></a> 
 
     <ul aria-labelledby="subLnk_01" class="sub_items"> 
 
      list of links 
 
     </ul> 
 
    </li>

+0

それは、ありがとう、働く。私はちょうどクリックでそれを包む必要があるので、ボタンがトグルされるたびにトリガします。 :-) –

+0

喜んであなたに:) – JYoThI

0

あなたはすでにあなたがその内のボタンを切り替えるそれぞれをループする必要がいけない、各「.togSubList」をループされているため。参照として "this"を使用し、それに応じて両方をターゲットにしてください。

唯一の問題は、ボタンが展開/折りたたまれるたびに関数を再実行する必要があることです。

$(".togSubList").each(function() { 
    var bob = $(this).find(".parent_link").text(); 
    //console.log(bob); 
    $(".sub-expand_collapse[aria-expanded='false']", this).attr("aria-label","expand " + bob); 
    $(".sub-expand_collapse[aria-expanded='true']", this).attr("aria-label”,”close " + bob);   
}); 
+0

help @ partypete25に感謝します。 –

関連する問題