我正在构建一个在不同页面上触发多个 javascript 的网站,每个页面都有不同的脚本。
我想要一个包含所有功能的 js 文件,但我不想在我不使用该脚本的页面上声明每个 javascript 文件。
我添加了不同的类(基于每个页面上使用的脚本)并且我正在使用这种方法:
if($('body').is('.wowJS')){
....
}
这是最有效的方法吗?还有其他方法吗?
最佳答案
使用此代码为特定页面执行 javascript。
var route = {
_routes: {}, // The routes will be stored here
add: function (url, action) {
this._routes[url] = action;
},
run: function () {
jQuery.each(this._routes, function (pattern) {
if (location.href.match(pattern)) {
// "this" points to the function to be executed
this();
}
});
}
}
// Will execute only on this page:
route.add('002.html',function (){
alert("Hello");
});
// You can even use regex-es:
route.add('.*.html',function (){
alert("Hellodaa");
});
route.run();
关于javascript - 不同页面调用不同的jQuery/JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24626365/