• jQuery核心之 $


    参考jQuery官网API文档
    $ 和 $() 的区别很重要:
    1、$(document).ready() 和 $(document).load() 的 区别:
        前者等到DOM准备好了之后就会触发,后者必须等到整个网页(包括图片,iframe)准备好了才触发。

        $(function(){
            alert("hello jquery");
        }); 是 $(document).ready(function(){
            alert("hello jquery");
        })的缩写。

    2、$ 即 为 jQuery的缩写,但是其他的框架可能也用 $ 来表示一些变量(并且在jquery之前加载),这个时候要避免这些冲突:
        var $j = jQuery.noConflict();    
        现在  $j 代表了之前的 $.

    或者将  $ 以参数的形式传递在ready函数中传递:
    <!-- Another way to put jQuery into no-conflict mode. -->
    <script src="prototype.js"></script>
    <script src="jquery.js"></script>
    <script>
    jQuery.noConflict();
    jQuery( document ).ready(function( $ ) {
    // You can use the locally-scoped $ in here as an alias to jQuery.
    $( "div" ).hide();
    });
    // The $ variable in the global scope has the prototype.js meaning.
    window.onload = function(){
    var mainDiv = $( "main" );
    }
    </script>


    如果 jquery在其他框架之前加载,那么:
    <!-- Loading jQuery before other libraries. -->
    <script src="jquery.js"></script>
    <script src="prototype.js"></script>
    <script>
    // Use full jQuery function name to reference jQuery.
    jQuery( document ).ready(function() {
    jQuery( "div" ).hide();
    });
    // Use the $ variable as defined in prototype.js
    window.onload = function() {
    var mainDiv = $( "main" );
    };
    </script>

     
    总之有以下几种方法:
    方法一,创建一个新的别名代替$
    <script src="prototype.js"></script>
    <script src="jquery.js"></script>
    <script>
    // Give $ back to prototype.js; create new alias to jQuery.
    var $jq = jQuery.noConflict();
    </script> 

    方法二、使用一个可以立即触发的函数表达式(将jQuery通过参数的形式传递给匿名函数):
    例如:
    <!-- 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> 

    方法三、在jQuery( document ).ready()中传递参数的形式:
    例如:
    <script src="jquery.js"></script>
    <script src="prototype.js"></script>
    <script>
    jQuery(document).ready(function( $ ) {
    // Your jQuery code here, using $ to refer to jQuery.
    });
    </script> 
    或者更加简洁:
    <script src="jquery.js"></script>
    <script src="prototype.js"></script>
    <script>
    jQuery(function($){
    // Your jQuery code here, using the $
    });
    </script>










  • 相关阅读:
    Struts2 中action之间的跳转(分享)
    从事web前端两年半后的迷茫
    阿里巴巴60万年薪抢毕业生 必须是公认技术牛人
    [置顶] LED办公楼宇照明节能方案及城市夜景照明节能方案
    线段树最后总结
    查看LINUX系统版本和硬件信息
    WIZnet即将推出高性能网络芯片W5500
    OA项目之分页
    json对象的封装与解析
    需求分析挑战之旅(疯狂的订餐系统)(8)——最后的疯狂
  • 原文地址:https://www.cnblogs.com/iceseal/p/3863942.html
Copyright © 2020-2023  润新知