jQuery Selection 和 库冲突问题

$() 和 $ 的区别

$() 和 CSS 选择器创建的对象叫 jQuery SelectionjQuery Object ;jQuery 对象有许多方法,这些方法都在命名空间 $.fn 下:

# .remove() 方法
$( "h1" ).remove(); 
jQuery Selection

$ 命名空间下也有一些方法,叫 utility-type methods
$$() 的区别相当于全局和局部的区别;

jQuery 与其他 JavaScript 库冲突

jQuery 默认有一个别名 $ , 可能会和其他库的 $ 变量名冲突:在 prototype.js 中,$ 相当于 document.getElementById()

jQuery $ 覆盖其他库的 $

  • jQuery.noConflict() 创建新的别名,将 $ 保留给其他 库 使用
<!-- Putting jQuery into no-conflict mode. -->
<script src="prototype.js"></script> 
<script src="jquery.js"></script>  <!-- jQuery 的 $ 变量名覆盖了 prototype 的 $ 变量名 -->
<script>
 
var $j = jQuery.noConflict();
// 为 jQuery 创建新的别名 $j, 将 $ 保留给 prototype
// $j is now an alias to the jQuery function; creating the new alias is optional.
 
$j(document).ready(function() {
    $j( "div" ).hide();  /* jQuery */
});
 
// The $ variable now has the prototype meaning, which is a shortcut for
// document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
window.onload = function() {
    var mainDiv = $( "main" );  /* prototype */
}
 
</script>

  • 在某一函数块里面使用 jQuery, 将$ 传给 jQuery(document).ready()
<!-- Another way to put jQuery into no-conflict mode. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>  <!-- jQuery 的 $ 变量名覆盖了 prototype 的 $ 变量名 -->
<script>
 
jQuery.noConflict(); /* 将 jQuery 的变量名保留给 prototype 使用 */
 

// 将变量名 $ 传给 .ready(),在该本地范围可以用 $ 作为 jQuery 的别名
jQuery( document ).ready(function( $ ) {
    // You can use the locally-scoped $ in here as an alias to jQuery.
    $( "div" ).hide();
});
 
// 在全局区范围内, $ 属于 prototype
// The $ variable in the global scope has the prototype.js meaning.
window.onload = function(){
    var mainDiv = $( "main" );
}
 
</script>

其他库覆盖 jQuery 的 $ 变量名

如果是其他库覆盖了 jQuery 的 $ 变量名,则当要使用 jQuery 时,直接使用 jQuery()

<script src="jquery.js"></script>
<script src="prototype.js"></script>

编写 jQeury 插件的模板

<!-- Using the $ inside an immediately-invoked function expression. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
 
jQuery.noConflict();
 
(function( $ ) {
    // Your jQuery code here, using the $
})( jQuery );
 
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,188评论 19 139
  • 1.几种基本数据类型?复杂数据类型?值类型和引用数据类型?堆栈数据结构? 基本数据类型:Undefined、Nul...
    伯纳乌的追风少年阅读 26,060评论 2 46
  • 纪实生活 体悟人生 今年不知道为什么? 我感觉吃到的水果 都没有这些水果的原来味道了? 难道你没有这种感触? 如果...
    木风恒阅读 1,153评论 0 0
  • 在寻找自我的时间里,做什么,看什么都带着怀疑的态度 我不确定这个决定是我内心真实的想法,我不确定我说的这句话出自我...
    羌芜阅读 1,693评论 0 0
  • 听歌不知什么时候被称为了一种爱好 幸好它是一种爱好 让我不至于没有爱好 绘画手残 失掉了当画家的梦想 舞蹈肢体不协...
    吴宥熙阅读 1,697评论 0 0

友情链接更多精彩内容