狂虐H5+移动跨平台开发js我爱编程

从零玩转jQuery-入口函数

2018-04-20  本文已影响498人  极客江南

jQuery入口函数

jQuery与JavaScript加载模式对比

<script>
        window.onload = function () {
            alert("hello lnj1"); // 不会显示
        }
        window.onload = function () {
            alert("hello lnj2"); // 会显示
        }
</script>
<script>
        $(document).ready(function () {
            alert("hello lnj1"); //会显示
        });
        $(document).ready(function () {
            alert("hello lnj2"); // 会显示
        });
</script>
<script>
        // 相当于这样写
        var test1 = function () {
            alert("hello lnj1");
        }
        var test2 = function () {
            alert("hello lnj2");
        }
        $(document).ready(test1);
        $(document).ready(test2);
</script>
<script>
        var test3 = function () {
            var abc = "123";
//            因为在同一个函数中,所以456覆盖123
//            var abc = "456"; 
            alert(abc);
        }
        test3();
        var test4 = function () {
            // 因为在不同函数中,所以不会影响
            var abc = "456"; 
            alert(abc);
        }
        test4();
</script>
window.onload $(document).ready()
执行时机 必须等待网页全部加载完毕(包括 图片等),然后再执行包裹代码 只需要等待网页中的DOM结构 加载完毕,就能执行包裹的代码
执行次数 只能执行一次,如果第二次,那么 第一次的执行会被覆盖 可以执行多次,第N次都不会被上 一次覆盖
简写方案 $(function () { });

        function test () {
            var customValue = 998;
            alert(customValue);
//            1.没有如下代码customValue就不是一个全局变量,函数执行完毕之后
//            customValue会被自动释放,test函数以外的地方访问不到customValue
//            2.加上如下代码之后customValue就会变成一个全局变量,函数执行完毕也不
//            会被释放,test函数以外的地方可以访问customValue
//            window.customValue = customValue;
        }
        test();
        alert(customValue);
window.jQuery = window.$ = jQuery;

<script>
        // 方式一
        $(document).ready(function () {
            alert("hello lnj");
        });
        // 方式二
        $(function () {
            alert("hello lnj");
        });
        // 方式三
        jQuery(document).ready(function () {
            alert("hello lnj");
        });
        // 方式四
        jQuery(function () {
            alert("hello lnj");
        });
</script>

解决$符号冲突问题

<script>
        // 在使用jQuery之前指定自定义符号
        jQuery.noConflict();
        // 使用 jQuery
        jQuery("div p").hide();
        // 使用其他库的 $()
        $("content").style.display = 'none';
</script>
<script>
        // 在使用jQuery之前指定自定义符号
        var nj = jQuery.noConflict();
        // 和使用$一样通过自定义符号调用jQuery
        nj(function () {
            alert("hello lnj");
        });
</script>
上一篇 下一篇

猜你喜欢

热点阅读