首页 > 解决方案 > 检查属性时如何将类添加到 ID?

问题描述

我正在研究一个也在此处描述的解决方案。

现在我很接近了,我想:

jQuery("#first-slide[data-isactiveslide="true"]").addClass("underline");

但我需要将类添加到我的 ID(我的按钮)。我该怎么做呢?我是这样想的,但它不起作用:

jQuery("#first-slide[data-isactiveslide="true"]"){
   jQuery("#my-button").addClass("underline");
});

任何帮助表示赞赏最好的问候,Skt

编辑这里是来自 chrome 开发工具的图像: 数据可见 true

标签: jquery

解决方案


您可以将选择器包装jQuery在 aif中以检查它是否找到任何东西,如果找到,请将类添加到按钮。

if (jQuery("#first-slide[data-isactiveslide='true']").length) {
  jQuery("#my-button").addClass("underline");
}
.underline { text-decoration: underline; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id='first-slide' data-isactiveslide='true'>#1</div>
<div id='second-slide' data-isactiveslide='false'>#2</div>

<button id='my-button'>Button</button>

编辑:相同的代码,isactiveslide=false显示按钮没有下划线

if (jQuery("#first-slide[data-isactiveslide='true']").length) {
  jQuery("#my-button").addClass("underline");
}
.underline { text-decoration: underline; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id='first-slide' data-isactiveslide='false'>#1</div>

<button id='my-button'>Button</button>


推荐阅读