使用JQuery:nth-child(n)选择器定位属于特定类的子元素

qyswt5oh  于 2023-06-05  发布在  jQuery
关注(0)|答案(1)|浏览(143)

我正尝试使用JQuery在特定的HTML按钮上应用一些CSS类。我试图定位的按钮是#left-well div中的第二个按钮。我的html中的所有按钮都有.target类,我使用的是$(".target:nth-child(2)").addClass("animated bounce")。但是在运行脚本时,两个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>
mgdq6dx1

mgdq6dx11#

只需将#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>

下次请看参考:Jquery Selectors

相关问题