javascript - 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>
我总是以拳头元素结束?有可能这样做吗?请有人帮忙。
解决方案
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>
推荐阅读
- matlab - 查找两个直方图交叉路径的位置 - MATLAB
- c# - WPF 数据触发器在使用(密封)后,无法修改
- reactjs - Highchart 未更新系列状态更改
- mysql - 选择仅具有一种值的行,而从一对中缺少其他值
- python - pandas.core.indexing.IndexingError:索引器太多
- android - Android KeyStore 操作失败:不支持的摘要
- sql - Oracle 复杂层次结构
- mysql - 将表导出为 CSV 时,导出向导非常慢
- javascript - 加载自定义对话框 Angular 2
- axios - Cache API 是否有 axios 缓存适配器?