我試圖使用JQuery在一個特定的html按鈕上應用一些CSS類。我嘗試定位的按鈕是# left-well div中的第二個按鈕。我的html中的所有按鈕都有。目標,我使用$(& quot;。目標:第n個孩子(2)& quot;).addClass(& quot;動畫彈跳& quot).但是在運行腳本時,div的第二個按鈕(#left-well和#right-well)成為目標。
如何編寫JQuery,使得只有#left-well中的第二個按鈕應用了這個類?
以下是代碼供您參考:
$(document).ready(function() {
$(".target:nth-child(2)").addClass("animated bounce");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container-fluid">
<h3 class="text-primary text-center">jQuery Playground</h3>
<div class="row">
<div class="col-xs-6">
<h4>#left-well</h4>
<div class="well" id="left-well">
<button class="btn btn-default target" id="target1">#target1</button>
<button class="btn btn-default target" id="target2">#target2</button>
<button class="btn btn-default target" id="target3">#target3</button>
</div>
</div>
<div class="col-xs-6">
<h4>#right-well</h4>
<div class="well" id="right-well">
<button class="btn btn-default target" id="target4">#target4</button>
<button class="btn btn-default target" id="target5">#target5</button>
<button class="btn btn-default target" id="target6">#target6</button>
</div>
</div>
</div>
</div>
只需將#left-well添加到選擇器中,如下所示:
$(document).ready(function() {
$("#left-well .target:nth-child(2)").addClass("animated bounce");
});
.animated,.bounce{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Only change code above this line -->
<div class="container-fluid">
<h3 class="text-primary text-center">jQuery Playground</h3>
<div class="row">
<div class="col-xs-6">
<h4>#left-well</h4>
<div class="well" id="left-well">
<button class="btn btn-default target" id="target1">#target1</button>
<button class="btn btn-default target" id="target2">#target2</button>
<button class="btn btn-default target" id="target3">#target3</button>
</div>
</div>
<div class="col-xs-6">
<h4>#right-well</h4>
<div class="well" id="right-well">
<button class="btn btn-default target" id="target4">#target4</button>
<button class="btn btn-default target" id="target5">#target5</button>
<button class="btn btn-default target" id="target6">#target6</button>
</div>
</div>
</div>
</div>
下一篇c 中 json