在特定页面/ body类上执行JavaScript代码的最佳方法?

时间:2015-06-17 22:54:46

标签: javascript jquery

我知道有为此制作的库,例如require.js,但我不想要任何复杂的东西。我只想运行在代码上有特定类时运行的JS代码。

我的尝试是为每个页面代码创建函数,以及检查正文是否具有执行代码的类名,然后运行它的函数。

   var body = $('body');

   initPageOnClass('.home', initFrontPage());

   function initPageOnClass(className, func) {
    if (body.hasClass(className)) {
        return func;
    }
   }

   function initFrontPage(){ 
    // some code for the frontpage
   }

哪个有效,但我担心这可能是不好的做法。是吗?我知道有更多的页面,会有更多的功能:

   initPageOnClass('.home', initAboutPage());

   initPageOnClass('.subscriptions', initSubscriptionPage());

   initPageOnClass('.team', initTeamPage());

但我不确定这是不是一个大的,或者是什么。我想这样做。

执行此任务的正确或最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

我宁愿在这种情况下使用一些属性和函数映射。您的标记将定义mim = imread('http://i.stack.imgur.com/RWBDS.jpg'); %we average all 3 color channels (note this isn't exactly equivalent to %rgb2gray) grayscale = uint8(mean(mim,3)); %now we say if all channels (r,g,b) are within some threshold of one another %(there's probabaly a better way to do this) my_gray_thresh=25; graymask = (abs(mim(:,:,1) - grayscale) < my_gray_thresh)... & (abs(mim(:,:,2) - grayscale) < my_gray_thresh)... & (abs(mim(:,:,3) - grayscale) < my_gray_thresh); figure(1) imshow(graymask); 属性:

role

脚本可能如下:

<body role=home>...</body>

然后检查我的spapp - 这很简单(60 LOC)

答案 1 :(得分:0)

我认为你是在正确的道路上,但是没有完全正确执行,如果你要检查一堆不同的类/功能,那么我建议采用表驱动的方法,所以你可以通过添加/删除/修改表中的项而不是编写新代码来维护它:

var bodyClassList = {
    "home": initFrontPage,
    "subscriptions": initSubscriptionPage,
    "team": initTeamPage
};

function runBodyInit() {
    var body = $(document.body);
    $.each(bodyClassList, function(cls, fn) {
        if (body.hasClass(cls) {
            // if class found, execute corresponding function
            fn();
        }
    });
}

runBodyInit();

或者,如果您在document.ready上执行此操作,那么您可以这样做:

$(document).ready(function() {
    var bodyClassList = {
        "home": initFrontPage,
        "subscriptions": initSubscriptionPage,
        "team": initTeamPage
    };
    var body = $(document.body);
    $.each(bodyClassList, function(cls, fn) {
        if (body.hasClass(cls) {
            // if class found, execute corresponding function
            fn();
        }
    });
});