【问题标题】:jquery direct id selection doesnt work, tag[id] selection does work [duplicate]jquery直接id选择不起作用,标签[id]选择起作用[重复]
【发布时间】:2018-03-28 23:06:07
【问题描述】:
我对 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>
【问题讨论】:
标签:
javascript
jquery
html
【解决方案1】:
: 在 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>
【解决方案2】:
您使用的 id 包含冒号 :,这是识别伪类和 jQuery 扩展的方式。为了让选择器引擎将其视为 id,您必须使用 \\ 对其进行转义。
当使用[id="1_9:15"] 时,您不会遇到同样的问题,因为 id 用括号括起来并且很容易识别。
示例:
/* Select the div by id escaping the colon. */
console.log($('#1_9\\:15')[0]);
/* Select the div using by id 'the attribute way'. */
console.log($('div[id="1_9:15"]')[0]);
/* Select the div using a pseudo-class. */
console.log($('div:first-child')[0]);
<script src="//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>