为什么 jQuery 的 last() 不能处理最后一次出现的 HTML 元素?

rup*_*317 0 css jquery

概述:

在下面的代码中,我应该突出显示 id = "sample" 的 html 元素的最后一次出现,即“这是最后一段”。然而,“这是第一段”却被突出显示。

问题:

1)为什么 $("#sample:last").css("background-color", "yellow") 不突出显示最后一段?

2)当我更改为 $("p#sample:last").css("background-color", "yellow") 时,最后一段会突出显示。为什么这可行,而不是问题 1 中的场景?

  <!DOCTYPE html>
  <html>
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
        $(document).ready(function(){
            $("#sample:last").css("background-color", "yellow");
        });
      </script>
    </head>
    <body>

      <p id="sample">This is the first paragraph.</p>
      <p id="sample">This is the second paragraph.</p>
      <p id="sample">This is the last paragraph.</p>

    </body>
  </html>
Run Code Online (Sandbox Code Playgroud)

Wou*_*man 5

问题是你使用的是 id 而不是类。一个 id 只能使用一次。正确的做法是为它们提供相同的类,并结合使用类选择.:last

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>

<script>
  $(document).ready(function() {
    $(".sample:last").css("background-color", "yellow");
  });

</script>



<p class="sample">This is the first paragraph.</p>
<p class="sample">This is the second paragraph.</p>
<p class="sample">This is the last paragraph.</p>
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/gt4L7zt2/