获取文本并在每个文本上使用 aria-label

Get text and use for aria-label on each

我想从每个 a.parent_link 中获取文本并将其作为 aria-label 应用于每个相应的切换按钮 (button.sub-expand_collapse)。我想要的最终结果是 if aria-expanded = true add aria-label= close + (text) and if aria-expanded = false add aria-label= expand + (text).

第一部分给我正文

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

但我无法让每个人都添加 aria-label。

     $(".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>

因为您已经在遍历每个“.togSubList”,所以您不需要遍历其中的每个切换按钮。只需使用 "this" 作为参考并相应地定位两者。

唯一的问题是当按钮 expanded/collapsed 时,您将需要重新 运行 函数。

$(".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);        
});

你不需要每个函数的第二个,因为在 LI 里面你只有一个元素,所以只需要使用 node traverse 。和 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>