我可以为jQuery提供默认的"上下文"吗?

Dav*_*esh 4 javascript iframe jquery

背景:

jQuery(selector, context)可以提供jQuery选择器调用的第二个"context"参数(例如:),以便为选择器引擎提供从中下降的起点.

如果您需要控制IFRAME中的内容(在同一个域中),这通常很有用.你只需传递iframe.contentWindow.document"context"参数.

如果在使用jQuery的IFRAME中加载任何JavaScript代码,并且从外部窗口的范围内调用,那么对该代码的任何引用$jQuery实际上都是jQuery来自外部窗口的实例.

当IFRAME中的JavaScript代码(比如Bootstrap.js)做类似的事情$(document)(或者做一些没有"context"参数的其他选择器)时会出现问题.当从外部窗口调用该代码(在iframe中定义)时,从外部窗口document引用HTMLDocument元素 - 这通常不是期望的结果.

题:

能够创建一个具有默认"上下文"参数的jQuery的词法范围副本/包装将是非常有用的,由任何人创建它.

例:

// jQuery already exists out here
var iframe = document.createElement('IFRAME');
iframe.addEventListener('DOMContentLoaded', function(){

    // code in here can already refer to $ for 'outer' jQuery

    // code in here can refer to $local for 'inner' jQuery by virtue of...
    var $local = jQueryWithContext($, iframe.contentWindow.document);

    // code loaded with IFRAME will use $local by virtue of ...
    iframe.contentWindow.jQuery = iframe.contentWindow.$ = $local;

});
iframe.src = '/path/to/iframe/content.html';
Run Code Online (Sandbox Code Playgroud)

问题是,是否可以写jQueryWithContext上面的内容?

为什么?

有时您希望隔离第三方HTML组件(从安全角度来看,您相信它们)从CSS/JavaScript污染角度来看是错误的.

Bootstrap.js就是一个很好的例子.它调用$(document)了一些,并进行其他类似的无上下文选择器调用.如果jQuery可以按照我描述的方式重新定义,那么这个"非最佳"编写的库可以很容易地被隔离.

另外,$.data(el, ...)从两个框架中使用相同的集合可能非常有用,如果没有一些上下文管理,这非常棘手.

Sim*_*ias 6

实际上,它会很简单:

function jQueryWithContext( selector, context ) {
  // I added the possibility to overwrite the context here, but you could delete
  return $( selector, context || iframe.contentWindow.document );
}
jQueryWithContext( '#main' ).show();
Run Code Online (Sandbox Code Playgroud)

但要强迫它插件,你可能需要这样:

jQuery.noConflict(); // keep the real jQuery for now
$ = function( selector, context ){
  return new jQuery.fn.init( selector, context || iframe.contentWindow.document );
};
$.fn = $.prototype = jQuery.fn;
jQuery.extend( $, jQuery ); // copy static method
// Then override default jQuery
jQuery = $;
Run Code Online (Sandbox Code Playgroud)

这种工作,但它可能打破一些用法$()(也许不是现在,但它可能在未来的jQuery版本,或任何时候context参数的存在打破正常行为).

  • jQuery有很多其他方法可以用$ .something调用(而不是选择器调用).如果这些方法在没有内容的情况下进行内部选择器调用,则这可能是一种有限的方法.你认为情况可能如此吗? (2认同)