ID Selector (“#id”)

id selector

version added: 1.0jQuery('#id')

  • id
    一个用来搜索的ID,通过指定一个元素的id属性。

描述: 选择一个具有给定id属性的单个元素。

对于ID选择,jQuery使用JavaScript函数document.getElementById(),这是非常有效的。当另一个选择是附加的ID选择器,比如h2#pageTitle,在确定作为匹配的元素前,jQuery执行一个额外的检查。

一如往常,记得作为一个开发者,你的时间通常是最宝贵的资源。不要注重速度优化的选择器,除非它很清楚,性能也需要改进。

每个id值必须是在一个文件中只能使用一次。如果一个以上的元素分配了相同的ID,查询将只选择该ID第一个匹配的DOM元素。但这种行为不应该发生;有超过一个元素的文件使用相同的ID是无效的。

如果ID包含如时间或冒号字符,你必须将 这些字符反斜杠转义.

Examples:

Example: Finds the element with the id "myDiv".

<!DOCTYPE html>
<html>
<head>
  <style>
  div {
    width: 90px;
    height: 90px;
    float:left;
    padding: 5px;
    margin: 5px;
    background-color: #EEEEEE;
  }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <div id="notMe"><p>id="notMe"</p></div>

  <div id="myDiv">id="myDiv"</div>
<script>$("#myDiv").css("border","3px solid red");</script>

</body>
</html>

Demo:

Example: Finds the element with the id "myID.entry[1]". See how certain characters must be escaped with backslashes.

<!DOCTYPE html>
<html>
<head>
  <style>
  div {
    width: 300px;
    float:left;
    padding: 2px;
    margin: 3px;
    background-color: #EEEEEE;
  }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <div id="myID.entry[0]">id="myID.entry[0]"</div>

  <div id="myID.entry[1]">id="myID.entry[1]"</div>
  <div id="myID.entry[2]">id="myID.entry[2]"</div>
<script>$("#myID\\.entry\\[1\\]").css("border","3px solid red");</script>

</body>
</html>

Demo:

jQuery 1.6 API 中文版Clove整理、修订