Javascript 如果 aria-expanded === true,则添加类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32399221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 08:00:13  来源:igfitidea点击:

Adding class if aria-expanded === true

javascriptjquery

提问by Julian Samarjiev

How can I go about toggling a class if aria=expanded === true? I have the following markup:

如果 ,我该如何切换课程aria=expanded === true?我有以下标记:

html

html

<a id="{{content.static.productDetailsToggleId}}" class="collapsed pdp-accord-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">{{content.static.productDetailsText}}<img class="accordion-plus" src="{{meta.assetsPath}}img/plus79.png" alt="accordion content">
</a>

js

js

$(function () {
  if ($('pdp-accord-toggle').attr('aria-expanded') === true) {
    $(this).find(".accordion-plus").toggleClass("accordion-minus");
  }
})

edit - more info

编辑 - 更多信息

Basically I watch to switch between a plusicon and a minusicon, replacing the imgin the .accordion-classwith content: url(another image);. Here is my CSS as well.

基本上我观看到一个之间切换plus图标和minus图标,取代了img.accordion-classcontent: url(another image);。这也是我的 CSS。

css

css

.accordion-plus {
  height: 1em;
  float: right;
  margin-right: 1em;
}

.accordion-minus {
  opacity: .5;
  content: url(../../assets/img/minus-1.png);
}

回答by Michael

looks like you're just missing the class prefix on the selector

看起来您只是缺少选择器上的类前缀

  if ($('.pdp-accord-toggle').attr('aria-expanded') === "true") {
  }

it returns a string aswell, so wrap the true in quotes

它也返回一个字符串,因此将 true 用引号括起来

回答by Monochrome Yeh

this would be easier

这会更容易

$("#pdp-accord-toggle[aria-expanded='true']").find(".accordion-plus")