【问题标题】:Get text and use for aria-label on each获取文本并用于每个 aria-label
【发布时间】:2017-07-10 06:39:58
【问题描述】:

我想从每个 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>

【问题讨论】:

标签: jquery function label each


【解决方案1】:

您不需要第二个每个函数,因为在 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>

【讨论】:

  • 这行得通,谢谢。我只需要将它包装在点击中,以便每次切换按钮时都会触发它。 :-)
  • 很高兴为您提供帮助:)
【解决方案2】:

因为您已经在遍历每个“.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);        
});

【讨论】:

  • 感谢@partypete25 的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-17
  • 2022-06-10
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 2017-07-29
  • 1970-01-01
相关资源
最近更新 更多