首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >仅在父链接的子页上显示类?

问仅在父链接的子页上显示类?
EN

Stack Overflow用户
提问于 2022-04-26 10:25:44
回答 1查看 31关注 0票数 0

因此,我想要实现的是只在某个父页面的子页面上显示一个类,并隐藏在其余的页面上。我查找了它,并了解到我可以通过页面ID使用jQuery实现这一点。但是这个子页面一直在更新,所以有什么方法可以让这个自动更新吗?

代码语言:javascript
复制
.sidebar {

示例页和子页;

代码语言:javascript
复制
https://example/event/   
https://example/event/pikachu

谢谢

EN

回答 1

Stack Overflow用户

发布于 2022-04-26 10:39:00

  1. 获取路径名:const { pathname } = window.location
  2. 检查它是否是你想要瞄准的路径名
  3. 向全班展示

例如:

代码语言:javascript
复制
https://www.example.com/path1  <-- Hide the class
https://www.example.com/path1/path2  <-- Show the class
https://www.example.com/path1/path3  <-- Show the class
https://www.example.com/path1/path2/path4  <-- Show the class
etc...
代码语言:javascript
复制
// .sidebar class allowed only for sub paths of /path1
// This is the logic //////////////////////////
const { pathname } = window.location;
const target = /^\/path1.*/gim;
if (target.test(pathname) && pathname !== '/path1')
node.classList.add('sidebar');
else node.classList.remove('sidebar');
///////////////////////////////////////////////

您可以测试演示这里

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72012338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档