-1

我想将位置哈希中的内容映射到字符串。映射必须基于以下模式(:Placeholder 可以是任意数字,也许是 RegEx?)。在函数中处理这个问题的最佳方法是什么?

    'news/:NewsID/dup' => 'newsDuplicate',
    'news/:NewsID' => 'newsDetail',
    'news/:NewsID/authors' => 'authorsList',
    'news/:NewsID/authors/' => 'authorsList',
    'news/:NewsID/authors/create' => 'authorsCreate',
    'news/:NewsID/authors/:AuthorID' => 'authorDetail',
    'news/:NewsID/authors/:AuthorID/orders' => 'orders',
    'news/:NewsID/authors/:AuthorID/workflow' => 'workflow',
    'news/:NewsID/authors/:AuthorID/tags' => 'tags'

我试图在导航中突出显示正确的按钮,并想要一个像 handleNav() 这样的函数,它会根据模式突出显示正确的按钮。

例如,当在http://mydomain.com#!news/123/authors/987时,我可以这样做:

function handleNav() {
  var current = ?? //get mapped string above
  $('button.' + current).addClass('active').siblings().removeClass('active');
}

如何根据映射获得上面的“当前”变量?不确定一堆 if-else 语句是否是最好的方法,而且我不太了解正则表达式。感谢您的任何帮助或见解。

4

1 回答 1

0

也许在读取映射之前规范化字符串?像这样的东西:

var map = {
  'news/ID/dup' : 'newsDuplicate',
  'news/ID' : 'newsDetail',
  'news/ID/authors' : 'authorsList',
  'news/ID/authors/' : 'authorsList',
  'news/ID/authors/create' : 'authorsCreate',
  'news/ID/authors/:AuthorID' : 'authorDetail',
  'news/ID/authors/:AuthorID/orders' : 'orders',
  'news/ID/authors/:AuthorID/workflow' : 'workflow',
  'news/ID/authors/:AuthorID/tags' : 'tags'
}

function normalize(str) {
    return str.replace(/news\/\d+/,'news/ID')
}

var current = map[normalize(url)];
于 2012-11-26T14:55:58.223 回答