DIV CSS 佈局教程網

jQuery context 屬性用法詳解:找出搜尋的起點節點
編輯:JQuery特效代碼     

context 屬性回傳的是傳給 jQuery() 的第二個參數,也就是這次查詢的「上下文節點」。若呼叫時沒有指定第二個參數,它就指向當前文檔 document。

語法結構

$("selector").context

範例一:預設情況

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>context 屬性</title>
<style type="text/css">
div
{
  width:150px;
  height:150px;
  border:1px solid blue;
}
</style>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    alert($("li").context);
  });
});
</script>
</head>
<body>
<div>
  <ul>
    <li>測試腳本</li>
  </ul>
</div>
<button>點擊測試</button>
</body>
</html>

沒有指定上下文時,$("li") 是從整個文件搜尋的,因此 context 就是 Document。在 IE 下會顯示 [object],其他瀏覽器則顯示 [object HTMLDocument]。

範例二:指定上下文

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>context 屬性</title>
<style type="text/css">
div
{
  width:150px;
  height:150px;
  border:1px solid blue;
}
</style>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    alert($("li", document.getElementById("myid")).context);
  });
});
</script>
</head>
<body>
<div>
  <ul id="myid">
    <li>測試腳本</li>
  </ul>
</div>
<button>點擊測試</button>
</body>
</html>

這次搜尋被限定在 id 為 myid 的 ul 之內,回傳值變成 [object HTMLUListElement](IE 下仍是 [object])。

版本提醒與替代寫法

context 屬性自 jQuery 1.10 起被標記為不建議使用,並在 jQuery 3.0 中移除。現代寫法建議直接用第二個參數完成限定,效果相同且語意更清楚:

// 舊寫法:$("li", document.getElementById("myid"))
// 建議寫法:
$("#myid li");
$("#myid").find("li");

指定上下文不只是為了效能(縮小搜尋範圍),更重要的是它能避免樣式或 id 命名衝突時誤抓到別處的元素,屬於值得養成的習慣。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved