萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery() 第二參數深度解析:context、ownerDocument、屬性對象三大用法

語法簽名

jQuery(selector [, context ])
jQuery(html [, ownerDocument ])
jQuery(html, attributes)

用法一:selector + context —— 限制搜索範圍

// 等價於 $(context).find(selector)
$('.child', '#parent');           // context 為選擇器字符串
$('.child', document.getElementById('parent')); // context 為 DOM 元素
$('.child', $('#parent'));        // context 為 jQuery 對象(取其 [0])

應用場景:在特定容器內查找、事件委託處理程序中縮小搜索範圍、iframe 跨文檔查找。

用法二:html + ownerDocument —— 指定創建 DOM 的文檔

// 默認在當前 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)時必須。

用法三:html + attributes 對象 —— 批量設置屬性/事件/數據

$('', {
  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...
  • HTML5 data-*:'data-x': 123
  • CSS 樣式:css: { ... }(調用 .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);
}

實戰技巧

  1. 動態創建表單提交:
    $('
    ', { action: '/submit', method: 'post', target: '_blank' }) .append($('', { name: 'token', value: getToken() })) .appendTo('body').submit().remove();
  2. 批量創建列表項:
    var $frag = $('
      '); data.forEach(item => $frag.append($('
    • ', { text: item.name, 'data-id': item.id }))); $('#container').append($frag);
  3. 事件委託上下文:
    $('#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 操作代碼。

copyright © 萬盛學電腦網 all rights reserved