gpt4 book ai didi

javascript - jQuery :last selector

转载 作者:太空宇宙 更新时间:2023-11-04 13:44:09 24 4
gpt4 key购买 nike

我正在使用这个 jQuery 代码

$('#share_module:last').css("background-color","red");

但它总是对第一个 #share_module

HTML 结构是这样的

<div id = "share_module" class = "id of the share">
//then stuff inside
</div>
<div id = "share_module" class = "id of the share">
//then stuff inside
</div>
<div id = "share_module" class = "id of the share">
//then stuff inside
</div>
<div id = "share_module" class = "id of the share">
//then stuff inside
</div>
<div id = "share_module" class = "id of the share">
//then stuff inside
</div>

但它只是得到第一个。有人可以帮忙吗?

最佳答案

不能有多个具有相同 ID 的 DOM 元素。那只是无效的 HTML。首先修复您的标记并删除此 id 属性,或者如果您希望脚本按预期运行,至少提供一个唯一的 id。因此,如果您想使用 :last 选择器,您可以使用类选择器而不是 id 选择器(例如,将 :last 选择器与 id 选择器一起使用是没有意义的,因为 id选择器只返回一个 DOM 元素 => 因为你的 DOM 中只能有一个具有这个 id 的元素 => 有意义):

<div class="share_module" >
//then stuff inside
</div>
<div class="share_module" >
//then stuff inside
</div>
<div class="share_module" >
//then stuff inside
</div>
<div class="share_module" >
//then stuff inside
</div>
<div class="share_module" >
//then stuff inside
</div>

一旦你有了有效的标记,你就可以使用 :last 选择器:

$('.share_module:last').css("background-color","red");

这是一个live demo .

关于javascript - jQuery :last selector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8770812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com