我对 jQuery id-selector 如何与我的 html 一起工作感到非常困惑。
使用$('#id')
选择器,jQuery 对象不包含我想要的 DOM 元素,使用 $('tag[id="id"]')
选择器虽然以某种方式工作。
有人可以解释为什么前者不起作用而后者起作用吗?
console.log($('#1_9:15')[0]);
console.log($('div[id="1_9:15"]')[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Monday</th>
<td>
<div id="1_9:15">FREE</div>
</td>
</tr>
</tbody>
</table>
最佳答案
:
在 jQuery 选择器中具有特殊含义。例如,要选择所有动画元素,您可以执行 $(":animated")
。这就是为什么你需要转义它:
console.log($('#1_9\\:15')[0]);
console.log($('div[id="1_9:15"]')[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Monday</th>
<td>
<div id="1_9:15">FREE</div>
</td>
</tr>
</tbody>
</table>
关于javascript - jquery 直接 id 选择不起作用,tag[id] 选择起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49537722/