不能同时通过类和数字 ID 选择 jquery 元素

Can't select jquery element by both class and numeric ID

本文关键字:ID 数字 选择 jquery 元素 不能      更新时间:2024-02-27
$(".associated_requests")
[<div class=​"associated_requests" id=​"0">​</div>​, 
<div class=​"associated_requests" id=​"1">​</div>​, 
<div class=​"associated_requests" id=​"2">​</div>​, 
<div class=​"associated_requests" id=​"3">​</div>​]
$(".associated_requests#0")
[]

我在语法上做错了吗?看这里,这似乎是可能的。

编辑:以下内容也失败:

$(".associated_requests #0")
[]
$("#0 .associated_requests")
[]
$("#0.associated_requests")
[]

在HTML5之前,id不能以数字开头。将其更改为以字母开头。即 item0item1item2

为什么不直接做$('#item0')?您不应该有重复的 ID

如果要根据索引选择div,则可以使用eq()方法:

$('.associated_requests').eq(0) // selects the first one
$('.associated_requests').eq(1) // selects the second one
var item0 = document.getElementById('0');
var item1 = document.getElementById('1');

或者你可以重命名你的ID,而不仅仅是一个数字添加,如id="id-0"

因此,您可以选择它作为$('#id-0.associated_content')