JQuery_JQuery冲突解决

最近在看《锋利的JQuery》感觉这本书讲的还不错。


我们在项目中除了JQuery 有可能要用到其他的JavaScript 库(Ext.js, prototype)时,有可能会与原来的JQuery 库冲突,下面记录了几个解决方法,供大家参考,mark一下


方法一  自定义快捷方式


(1) 使用JQuery作为调用 JQuery的快捷方式

<script>
        jQuery.noConflict();
        jQuery(function(){
            var $test = jQuery('#test');

            //jQuery获取元素内容
            console.log("第一种冲突解决方法 "+$test.html());

            //javaScript获取元素内容
            var dom = $test.get(0);
            for(var i = 0; i<dom.childNodes.length; i++){
                if(dom.childNodes[i].nodeType == 3){
                    console.log(dom.childNodes[i].nodeValue);
                }
            }
        });
    </script>




(2)使用自定义的符号作为快捷方式

 <script>
        var $j = jQuery.noConflict();
        $j(function(){
            //jQuery获取元素内容
            console.log("第二种冲突解决方法 "+$j('#test').html());
        });
    </script>





方法二 在函数内部使用JQuery方法


(1)

<script>
        jQuery.noConflict();
        jQuery(function($){
            //jQuery获取元素内容
            console.log("第三种冲突解决方法 "+$('#test').html());
        });
    </script>





(2)

<script>
        jQuery.noConflict();
        (function($){
            $(function(){
                //jQuery获取元素内容
                console.log("第四种冲突解决方法 "+$('#test').html());
            });
        })(jQuery);
    </script>




整体测试代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery冲突解决</title>
    <script src="js/jquery-1.11.3.js"></script>
    <script>
        jQuery.noConflict();
        jQuery(function(){
            var $test = jQuery('#test');

            //jQuery获取元素内容
            console.log("第一种冲突解决方法 "+$test.html());

            //javaScript获取元素内容
            var dom = $test.get(0);
            for(var i = 0; i<dom.childNodes.length; i++){
                if(dom.childNodes[i].nodeType == 3){
                    console.log(dom.childNodes[i].nodeValue);
                }
            }
        });
    </script>
</head>
<body>
    <div id="test">这是一个测试的节点</div>

    <script>
        var $j = jQuery.noConflict();
        $j(function(){
            //jQuery获取元素内容
            console.log("第二种冲突解决方法 "+$j('#test').html());
        });
    </script>

    <script>
        jQuery.noConflict();
        jQuery(function($){
            //jQuery获取元素内容
            console.log("第三种冲突解决方法 "+$('#test').html());
        });
    </script>

    <script>
        jQuery.noConflict();
        (function($){
            $(function(){
                //jQuery获取元素内容
                console.log("第四种冲突解决方法 "+$('#test').html());
            });
        })(jQuery);
    </script>
</body>
</html>




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值