javascript - 不同页面调用不同的jQuery/JS

标签 javascript jquery

我正在构建一个在不同页面上触发多个 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/

相关文章:

javascript - 在 DOMContentLoaded 上的 javascript 函数中声明全局常量

javascript - JavaScript html5 Canvas

javascript - 使用 jQuery 提交表单(json 编码、ajax、解析原始 url/方法)

javascript - Lightbox2 - 显示 div 的内容而不是图像

jquery - 相当于 native javascript 中的 $(this)

javascript - 针对特定 JavaScript 忽略 Cloudflare Automatic RocketLoader

javascript - PHP调用JS函数

javascript - 对数组对象进行分组,使具有相似键的对象不会放入同一组中

javascript - 请搜索 TreeView 帮助

javascript - 如何处理 "Failed to load resource"