在WordPress Sage的main.js中, 我们可以运行页面特定的JS:
var Sage = {
// All pages
'common': {
init: function() {
// JavaScript to be fired on all pages
}, finalize: function() {
// JavaScript to be fired on all pages, after page specific JS is fired
}
}, // Home page
'home': {
init: function() {
// JavaScript to be fired on the home page
}, finalize: function() {
// JavaScript to be fired on the home page, after the init JS
}
}, // About us page, note the change from about-us to about_us.
'about_us': {
init: function() {
// JavaScript to be fired on the about us page
}
}
};
但是, 如何在特定的单个或存档CPT页面上运行JS?
#1
在你希望JS触发的页面/帖子/档案的正文中检查类名, 并使用其中之一。例如, 如果你有一个名为” work”的自定义帖子类型, 则工作档案正文元素将具有一类post-type-archive-work。你可以用来触发特定的JS, 如下所示:
// Note the change from about-us to about_us.
'post_type_archive_work': {
init: function() {
// JavaScript to be fired on the 'work' archive
}
}
有关更多信息, 请查看Paul Irish的帖子
#2
乔什·埃利斯(Josh Ellis)的回答是正确的, 但有一点澄清。类路由器具有以下方法:
/**
* Fire Router events
* @param {string} route DOM-based route derived from body classes (`<body class="...">`)
* @param {string} [event] Events on the route. By default, `init` and `finalize` events are called.
* @param {string} [arg] Any custom argument to be passed to the event.
*/
fire(route, event = 'init', arg) {
const fire = route !== '' && this.routes[route] && typeof this.routes[route][event] === 'function';
if (fire) {
this.routes[route][event](arg);
}
}
使用身体上的任何类。例如:Sage 9的’teams-template-default single single-teams’=>’single_teams’或’singleTeams’。
评论前必须登录!
注册