尝试切换方法以在按钮单击时引入新的新类

我正在尝试使用nth-child()方法为特定的div元素引入新类,但是它不起作用! 难道我做错了什么? (请注意,菜单,容器和newClass已经在CSS部分中定义,在此不再显示。) 这是我正在尝试的:

$(function() {
  $("button").click(function {
    $("div:nth-child(2)").toggleClass("newClass");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Toggle CSS</button>
<div class="container">
  <div class="menu">
    <lu>
      <li>option 1</li>
      <li>option2</li>
      <li>option 3</li>
    </lu>
  </div>
</div>
评论
kqui
kqui

There are lots of mistakes in your code. Which div are you want to add a class newClass? I think your code should be like this

$(function() {
  $("button").on('click', function() {
    $("ul li:nth-child(2)").toggleClass("newClass");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Toggle CSS</button>
<div class="container">
  <div class="menu">
    <ul>
      <li>option 1</li>
      <li>option2</li>
      <li>option 3</li>
    </ul>
  </div>
</div>
点赞
评论
咕噜咕噜
咕噜咕噜

Here you have two div elements, each one them has only one child, and you trying to select the second child div:nth-child(2) which does not exist

点赞
评论