首页 > 解决方案 > JQuery 最后一个选择器没有按预期工作

问题描述

我有这个大概率。在我的代码中有具有相同 id 的元素(我知道这是不好的做法)所以我想要做的是选择最后一个,使用 jquery,元素来应用一些 css。按照逻辑,这应该是可行的。下面是代码

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

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

</body>
</html>

我总是以拳头元素结束?有可能这样做吗?请有人帮忙。

标签: javascriptjquerydomjquery-selectors

解决方案


ID 旨在在 html 文档中是唯一的。我还没有研究为什么这种特殊情况不适用于 jQuery,但我会以相同的方式编写框架。如果一个 id 只能有一个实例,那么就没有理由实现像“first”或“last”这样的伪选择器。

如果您将选择更改为基于类,它会起作用。我建议您停止使用同一 id 的多个实例。

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

<p class="i">This is the first paragraph.</p>
<p class="i">This is the second paragraph.</p>
<p class="i">This is the last paragraph.</p>

</body>
</html>


推荐阅读