Expressjs在partial中为li元素添加类

Expressjs add class to li element in partial

本文关键字:元素 添加 li 中为 partial Expressjs      更新时间:2023-09-26

我有一个局部菜单:

<ul id="submenu">
    <li><a href="/mypage/profile/<%=user[0].id  %>">Profile</a></li>
    <li><a href="/mypage/test/<%=user[0].id  %>">Test</a></li>
</ul>

和这些路线:

app.get('/mypage/profile/:id', function(req,res,next) {
    res.render('site/mypage/cv', {
        title: 'profile'
    });
});
app.get('/mypage/test/:id', function(req,res,next) {
    res.render('site/mypage/cv', {
        title: 'test'
    });
});

如何根据单击的链接将一类selected添加到li元素?

对于本例,您不需要任何服务器端东西,您可以通过简单的jQuery代码实现效果(记住在之前的页面中包含jQuery):

$(function() {
  // put the possible page titles here
  // they must be in the url also
  var possible_pages = ['profile', 'test'], 
      path = window.location.pathname,
      pattern, page, i, len;
  for (i = 0, len = possible_pages.length; i <= len; i++) {
    page = possible_pages[i];
    pattern = new RegExp(page);
    if (pattern.test(path)) {
      $('.submenu .' + page).addClass('selected');
      break;
    }
  }
});