gpt4 book ai didi

javascript - 根据人体类自动调用函数

转载 作者:行者123 更新时间:2023-11-29 22:02:01 24 4
gpt4 key购买 nike

我正在创建一个包含约 6 个页面的基本站点,我的 javascript 结构设置如下:

var MYSITE = {};

// this gets the class on the body in the HTML
MYSITE.getPage = function(){
var _bodyClass = $('body').attr('class').split(/\s/),
curPage = _bodyClass[ 0 ];
return curPage;
};

MYSITE.Common = (function(){
var init = function(){
// do global stuff
};

return {
init: init
}
})();

MYSITE.Home = (function(){
var init = function(){
// do homepage specific stuff
};
return {
init: init
}
})();

MYSITE.About = (function(){
var init = function(){
// do about page specific stuff
};
return {
init: init
}
})();

// etc

// DOM Ready
$(function() {
MYSITE.Common.init();

if( MYSITE.getPage() === 'home' ) {
MYSITE.Home.init();
}

if( MYSITE.getPage() === 'about' ) {
MYSITE.About.init();
}

// etc
});

我想在我的 HTML 中调用基于 body 类的特定函数。到目前为止我已经尝试过了并且它有效,但是每次我添加一个页面我都必须更新我的 JS。

如何根据 HTML 中的 body 类自动触​​发正确的模块函数?

最佳答案

使用body类引用对象中的属性名,首字母大写即可。

$(function() {
MYSITE.Common.init();

var site = MYSITE.getPage();

site = site.charAt(0).toUpperCase() + site.slice(1); // capitalize first

MYSITE[site].init();
});

关于javascript - 根据人体类自动调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23249761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com