【问题标题】:How to combine pathname with URL strings如何将路径名与 URL 字符串结合起来
【发布时间】:2020-05-03 23:48:31
【问题描述】:

我正在设置包含多个 URL 路径名的 javascript,但我不想为连续 URL 字符串设置新的“案例”。

是否有任何可能的解决方案来组合路径名案例而不是创建一个新的案例?

switch (window.location.pathname) {
case '/blog/category/style':
$(".wsite-sideblock h2.wsite-title").append("Style");
break;
case '/blog/category/style/2':
$(".wsite-sideblock h2.wsite-title").append("Style");
break;
case '/blog/category/style/3':
$(".wsite-sideblock h2.wsite-title").append("Style");
break;
.
.
.
case '/blog/category/style/10':
$(".wsite-sideblock h2.wsite-title").append("Style");
break;
}

我有一个想法,一个简单的技巧是像这样添加“+”......(但它不起作用)

case '/blog/category/style' + '/blog/category/style/2':

【问题讨论】:

  • 它们都是以数字结尾还是你只是举个例子?

标签: javascript string url location pathname


【解决方案1】:

如果你总是这样做,我认为你不需要使用 switch。将这些路径放在一个数组中,然后简单检查 window.location.pathname 是否在数组中,具体取决于添加的样式。

    const paths = ['/blog/category/style', '/blog/category/style/2', ..., '/blog/category/style/10'];
    if (paths.includes(window.location.pathname)) {
        $(".wsite-sideblock h2.wsite-title").append("Style");
    }

【讨论】:

    【解决方案2】:

    您可以使用这种 Switch Cases 组合它们(如果它们具有相同的输出命令):

    switch (window.location.pathname) {
    case '/blog/category/style':
    case '/blog/category/style/2':
    case '/blog/category/style/3':
    ...
    case '/blog/category/style/10':
    $(".wsite-sideblock h2.wsite-title").append("Style");
    break;
    }
    

    【讨论】:

      【解决方案3】:

      您实际上可以省略break 语句,控制将“通过”到下一个响应。

      let pathname = '/blog/category/style/3';
      
      switch (pathname) {
        case '/blog/category/style':
        case '/blog/category/style/2':
        case '/blog/category/style/3':
        case '/blog/category/style/10':
          console.log("Print this for any of the above cases");
          break;
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-13
        • 1970-01-01
        • 2011-08-02
        • 2021-03-15
        • 2016-11-07
        • 1970-01-01
        • 2018-09-08
        • 2021-04-08
        相关资源
        最近更新 更多