jQuery 選擇器接受第二個參數 context,限制搜尋範圍:
$(selector, context)
// 等同於
$(context).find(selector)
這在大型 DOM、局部更新、元件封裝中極為重要。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery 上下文選擇器示範</title>
<style>
.panel { border: 1px solid #ddd; border-radius: 8px; padding: 20px; margin: 20px; max-width: 500px; }
.panel h3 { margin-top: 0; color: #1976d2; }
input[type="text"] { width: 100%; padding: 8px; margin: 8px 0; box-sizing: border-box; }
button { padding: 8px 16px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>頁面層級輸入框 (不受影響)</h2>
<input type="text" placeholder="頁面級輸入框 1">
<input type="text" placeholder="頁面級輸入框 2">
<div class="panel" id="formPanel">
<h3>表單區域 (上下文範圍)</h3>
<input type="text" placeholder="表單輸入框 1">
<input type="text" placeholder="表單輸入框 2">
<input type="text" placeholder="表單輸入框 3">
<button id="btnTest">只修改表單內輸入框</button>
</div>
<script>
$(function() {
$('#btnTest').on('click', function() {
// 核心:上下文選擇器 - 僅在 #formPanel 內尋找 :text
$(':text', $('#formPanel')).val('我是表單內的文本框').css('border-color', '#1976d2');
// 等價寫法 (推薦,語意更清晰)
// $('#formPanel').find(':text').val('...');
});
});
</script>
</body>
</html>
| 類型 | 範例 | 說明 |
|---|---|---|
| jQuery 物件 | $('#form') | 最常用,內部元素已快取 |
| DOM 元素 | document.getElementById('form') | 原生元素,jQuery 內部轉換 |
| 選擇器字串 | '#form' | jQuery 會先查找 context,再找 selector |
| Document | document | 預設值,全域搜尋 |
$(context).find(selector)// 明確語意:先找容器,再找後代
const $panel = $('#formPanel');
$panel.find(':text').val('...');
$panel 重複使用$(selector, context) 在迴圈中重複呼叫// 差:每次迴圈都重新查找 context
for (let i=0; i<100; i++) {
$('input', '#form').val(i); // 每次都執行 $('#form') 查找
}
// 優:快取 context
const $form = $('#form');
for (let i=0; i<100; i++) {
$form.find('input').val(i);
}
class FormComponent {
constructor(containerSelector) {
this.$container = $(containerSelector); // 快取上下文
this.bindEvents();
}
bindEvents() {
this.$container.on('click', '.btn-submit', () => this.submit());
}
getValues() {
// 內部查找自動限制在容器範圍
return {
name: this.$container.find('[name="name"]').val(),
email: this.$container.find('[name="email"]').val()
};
}
submit() {
const data = this.getValues();
console.log('提交:', data);
}
}
// 頁面可實例化多個互不干擾的表單元件
const form1 = new FormComponent('#form1');
const form2 = new FormComponent('#form2');
$(selector, context) 會在 context 內「重新建立」選擇器引擎。
context.find(selector),無額外效能優勢。選擇器引擎 (Sizzle) 仍從 context 根節點開始遍歷。
.find() 的語法糖$container.find(selector) 形式,利於快取與閱讀this.$container 是標準模式