有2个js文件
test01.js
(function($){
test_function = function(str) {
alert(1+str);
};
test_function2= function(str) {
alert(2+str);
}
})(jQuery);
test02.js
(function($){
test_function = function(str) {
alert(3+str);
};
test_function2= function(str) {
alert(4+str);
}
})(jQuery);
调用文件test.html
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>New Tab</title>
<script src="jquery-1.6.2.min.js"></script>
<script src="test01.js"></script>
<script src="test02.js"></script>
<script type="text/javascript">
$(function(){
test_function("test");
test_function2("test");
});
</script>
</head>
<body>
</body>
</html>
由于test01.js和test02.js的函数重名,后载入的js方法会覆盖之前载入的同名js方法。
所以,test.html的执行结果是弹出3test和4test。
我的解决方法是:
test01.js
var test01 = {};
(function($){
test01.func = {
test_function:function(str) {
alert(1+str);
},
test_function2:function(str) {
alert(2+str);
}
}
})(jQuery);
test02.js
var test02 = {};
(function($){
test02.func = {
test_function:function(str) {
alert(3+str);
},
test_function2:function(str) {
alert(4+str);
}
}
})(jQuery);
test.html
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>New Tab</title>
<script src="jquery-1.6.2.min.js"></script>
<script src="test01.js"></script>
<script src="test02.js"></script>
<script type="text/javascript">
$(function(){
test01.func.test_function("test");
test01.func.test_function2("test");
test02.func.test_function("test");
test02.func.test_function2("test");
});
</script>
</head>
<body>
</body>
</html>
test.html的执行结果正确,没有因为test01.js和test02.js函数名相同就相互覆盖。
参数网址:
http://qilei.org/201005/how-to-make-the-func-name-no-clrash/
http://www.cnblogs.com/5201314/archive/2009/05/22/1487213.html