jQuery prototype冲突的2种解决方法(附demo示例下载)
本文实例分析了jQueryprototype冲突的2种解决方法。分享给大家供大家参考,具体如下:
jquery和prototype怎么会冲突,归根到底就是因为他们二个都用到了$,同时用,混淆了。这个问题解决过不下5次,每次解决都要查一下。淡疼,嘿嘿。
方法一、在jquery的核心库文件中加代码。
1、一般是jquery.js,或者jquery.min.js,有的带版本号的。知道是哪个文件就行。
})(window); jQuery.noConflict();//最后面,加上这一行。
2、加载测试jquery和prototype文件
<scripttype="text/javascript"src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script> <scriptsrc="jquery.min.js"></script>
3、js代码写法
<scripttype="text/javascript">
alert('prototypevalue:'+$('test').value);//prototype写法
jQuery(document).ready(function($){//注意这里的,jQuery和$
alert('jqueryvalue:'+$('#test').val());//jquery写法
});
</script>
推荐这种方法,这种方法比较一劳永逸
完整demo代码如下:
<html>
<head>
<scripttype="text/javascript"src="./prototype.js"></script>
<scriptsrc="jquery.min.js"></script>
</head>
<body>
<form>
<inputid="test"type='text'name='test'value='test'/>
</form>
<scripttype="text/javascript">
alert('prototypevalue:'+$('test').value);
jQuery(document).ready(function($){
alert('jqueryvalue:'+$('#test').val());
});
</script>
</body>
</html>
方法二、在调用jquery的地方,解决冲突
1、加载测试jquery和prototype文件
//jquery和prototype,没有先后顺序,谁先谁后都一样。 <scripttype="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <scripttype="text/javascript"src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script>
2、js代码
<scripttype="text/javascript">
jQuery.noConflict();//解决冲突,这个一定要放在js代码的最前面,不然就会报错了。
alert('prototypevalue:'+$('test').value);
jQuery(document).ready(function($){
alert('jqueryvalue:'+$('#test').val());
});
</script>
这种方法比较适合jquery的核心源文件不在自己的服务器上,或者jquery代码比较少的情况。该示例demo点此查看。
完整demo可点击此处本站下载。
希望本文所述对大家jQuery程序设计有所帮助。