简而言之,我有两个具有相同类的按钮,其中一个具有属性 data-toggle='modal'
。我使用这个属性来检测按钮。
我需要更改没有属性 data-toggle
的按钮的颜色,我无法使用 className 来定位它,因为它们都具有相同的属性。
在js点击函数中,我使用三元条件表示:如果按钮有属性'data-toggle
'那么什么都不做,否则removeClass btn--ghost
和addClass btn--plain
。但它不起作用。
PS:btn--plain
是用于给按钮一个 bgcolor 而不是 btn--ghost
的类名。
这是js:
if ($('.o-block-global .btn--link').length) {
$('.btn--primary').on("click", function (e) {
console.log("iiiiii", $(this));
$(this).attr("data-toggle" ? "" : $(this).removeClass("btn--ghost").addClass("btn--plain"));
});
}
这是 HTML:
<div class="o-block-global__links link_choice ">
<button type="button" class="btn btn--ghost btn--primary">
OUI
</button>
<button type="button" class="btn btn--ghost btn--primary" data-toggle="modal" data-target="#modalChoice2">
NON
</button>
</div>
答案 0 :(得分:1)
您可以检查 attr
值是否为 undefined
或不使用 (typeof $(this).attr("data-toggle")) !== 'undefined'
演示代码:
$('.btn--primary').on("click", function(e) {
//check if the attr type is not undefined
(typeof $(this).attr("data-toggle")) !== 'undefined' ? "" : $(this).removeClass("btn--ghost").addClass("btn--plain");
});
.btn--ghost {
color: red;
}
.btn--plain {
color: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="o-block-global__links link_choice ">
<button type="button" class="btn btn--ghost btn--primary">
OUI
</button>
<button type="button" class="btn btn--ghost btn--primary" data-toggle="modal" data-target="#modalChoice2">
NON
</button>
答案 1 :(得分:0)
要做到这一点,请使用 :active selector
。 HTML:
<button>Click Me!</button>
button{
background:green;
}
button:hover{
background:lightgreen;
}
button:active{
background:red;
}