首页 > 解决方案 > jQuery命令没有给出想要的结果

问题描述

我希望active使用 html jquery 添加到最后一个 img 元素的 className

我在 HTML 和 jquery 中有一些元素,如下所示:

function initialSteps() {
  $(".row").find("column:last").find("img:first").className += " active";
  // this does not work either
  //$(".row").find("column:last").find("demo cursor:last").className += " active";

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <div class="column">
    <img class="demo cursor" src="img00.jpg">
  </div>
  <div class="column">
    <img class="demo cursor" src="img01.jpg">
  </div>
  <div class="column">
    <img class="demo cursor" src="img02.jpg">
  </div>
  <div class="column">
    <img class="demo cursor" src="img03.jpg">
  </div>
  <div class="column">
    <img class="demo cursor" src="img04.jpg">
  </div>
  <div class="column">
    <img class="demo cursor" src="img05.jpg">
  </div>
</div>

但是,它不起作用。有人可以告诉我我做错了什么吗?

标签: jqueryhtmlcss

解决方案


你做错了。您不能使用“+”运算符为类附加值。

jQuery 具有在任何元素中添加新类的内置方法。

您可以使用以下功能代替您的功能。

function initialSteps() {
   $(".row").find(".column:last").find("img:first").addClass("active");
});

推荐阅读