【问题标题】:How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?如何使用 Jquery 如何更改 dom 元素(Bootstrap)的 aria-expanded="false" 部分?
【发布时间】:2015-03-01 09:04:39
【问题描述】:

我有以下元素:

<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">

我想使用 jquery(或者只使用 javascript)来更改 aria-expanded 字段以在真假之间切换。

我该怎么办?

谢谢!

【问题讨论】:

  • 不添加另一个答案,即使它不完全是现有答案的副本。但是如果你想使用普通的 JS 来做到这一点,你可以使用el.setAttribute("aria-expanded", true); 其中el 是可以使用getElementByIdquerySelectorgetElementsByClassName 获得的元素。

标签: javascript jquery html css twitter-bootstrap


【解决方案1】:

您可以使用.attr() 作为您计划切换它的一部分:

$("button").attr("aria-expanded","true");

【讨论】:

  • 使用.prop 并拥有$("button").prop('aria-expanded', true) 怎么样?我读到.attr 适用于 jQuery v1.5 及以下版本,而.prop 适用于 jQuery v1.6 及以上版本。
  • 由于某种原因,$(this).find('.dropdown-toggle').prop('aria-expanded', 'true') 在这种情况下对我不起作用,而 attr() 对我有用。? 我正在使用 jquery v3.2.1
【解决方案2】:

由于问题要求使用 jQuery vanilla JS,因此这里是 vanilla JS 的答案。

我在下面的演示中添加了一些 CSS,以便在按钮的 aria-expanded 设置为 true 时将按钮的字体颜色更改为红色

const button = document.querySelector('button');

button.addEventListener('click', () => {
  button.ariaExpanded = !JSON.parse(button.ariaExpanded);
})
button[aria-expanded="true"] {
  color: red;
}
&lt;button type="button" aria-expanded="false"&gt;Click me!&lt;/button&gt;

【讨论】:

    【解决方案3】:

    基于元素点击的引导切换类。点击后提及 aria-expanded 值

    $("#navbar-btn-icon").click(function(e) {
      var menuItem = $(this);
    
      if (menuItem.attr("aria-expanded") === "true") {
        $(".navbar-toggler-icon").addClass('clicked');
      }
      else if (menuItem.attr("aria-expanded") === "false") {
        $(".navbar-toggler-icon").removeClass('clicked');
      }
    
    });
    

    在 CSS 中添加关闭按钮图标。点击更改

    .navbar-toggler-icon.clicked{
        background-image: url("close-icon.png");
        transition: 0.2s ease-in;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-17
      • 1970-01-01
      • 2022-06-20
      • 2023-01-16
      • 2018-01-26
      • 2019-02-10
      • 2016-08-12
      • 1970-01-01
      相关资源
      最近更新 更多