jQuery(selector [, context ])
jQuery(html [, ownerDocument ])
jQuery(html, attributes)
// 等價於 $(context).find(selector)
$('.child', '#parent'); // context 為選擇器字符串
$('.child', document.getElementById('parent')); // context 為 DOM 元素
$('.child', $('#parent')); // context 為 jQuery 對象(取其 [0])
應用場景:在特定容器內查找、事件委託處理程序中縮小搜索範圍、iframe 跨文檔查找。
// 默認在當前 document 創建
$('test');
// 在 iframe 文檔中創建元素
var iframeDoc = $('#myIframe')[0].contentDocument;
$('test', iframeDoc).appendTo(iframeDoc.body);
// window.open 打開的新窗口
var win = window.open();
$('Hello
', win.document).appendTo(win.document.body);
罕見但處理跨文檔操作(iframe、popup、Shadow DOM)時必須。
$('', {
type: 'text',
value: 'Test',
id: 'myInput',
'data-role': 'editor',
css: { border: '1px solid #ccc', padding: '5px' },
on: {
focusin: function() { $(this).addClass('active'); },
focusout: function() { $(this).removeClass('active'); },
change: function() { console.log('changed:', this.value); }
}
}).appendTo('form');
屬性對象鍵支持:
id, class, name, value, href, src...'data-x': 123css: { ... }(調用 .css())on: { event: handler }(調用 .on())val: 'text'(調用 .val())、text: '...'、html: '...'// 簡化版 jQuery.fn.init 邏輯
if (typeof selector === 'string' && selector.charAt(0) === '<') {
// HTML 字符串創建元素
var doc = context?.ownerDocument || context || document;
var elem = doc.createElement(...);
if (attributes) $(elem).attr(attributes); // 或遍歷調用對應方法
return $(elem);
}
$('
var $frag = $('');
data.forEach(item => $frag.append($('- ', { text: item.name, 'data-id': item.id })));
$('#container').append($frag);
$('#list').on('click', '.item', function() {
var $detail = $('.detail', this); // 當前項內查找
});
$('', { appendTo: '#box' }) 才支持 appendTo 鍵,單純傳 DOM 不會自動插入。
- context 傳 jQuery 對象:內部取
context[0],傳選擇器字符串會重新查找,性能略低。
- attributes 中的事件鍵:必須用
on: { click: fn },寫 click: fn 會被當作屬性設置(無效)。
總結
jQuery() 第二參數三大用法各有專用場景:context 限制查找範圍、ownerDocument 跨文檔創建、attributes 批量配置元素。掌握後可寫出更簡潔、高效的 DOM 操作代碼。
- 上一篇程序編程: AngularJS 多模塊動態加載:解決重複 bootstrap 導致的模塊衝突
- 下一篇程序編程: 原生 JS 仿 QQ 郵箱彈出確認框:拖拽、關閉、遮罩完整實現