jQuery:如果关键字在URL中,则将类添加到正文中

jQuery:如果关键字在URL中,则将类添加到正文中,jquery,Jquery,我有如下URL: 我正在寻找一段jQuery代码,如果某个关键字是URL的一部分,它会将某个类添加到正文中 有人有什么想法吗?我知道这是可能的,但我找不到任何有效的建议 e、 g.应该像这样创建HTML: <body class="keyword1"> bla bla bla </body> 呜呜呜呜 谢谢你的提示 您可以使用window.location.hash在页面加载时尝试此操作: $(document).ready(function() { var

我有如下URL: 我正在寻找一段jQuery代码,如果某个关键字是URL的一部分,它会将某个类添加到正文中

有人有什么想法吗?我知道这是可能的,但我找不到任何有效的建议

e、 g.应该像这样创建HTML:

<body class="keyword1">
bla bla bla
</body>

呜呜呜呜

谢谢你的提示

您可以使用
window.location.hash
在页面加载时尝试此操作:

$(document).ready(function() {
   var hash = window.location.hash;
   if (hash) {
      hash = hash.replace('#', '');
      $("body").addClass(hash);
   }
});

您可以使用
window.location.href
获取完整URL,然后使用任意字符将其拆分为数组,然后将此字符串作为类添加到正文中

示例

$(document).ready(function() {
    var url = window.location.href
    $("body").addClass(url.split("#")[1])
});

您可以在“window.location.href.indexOf(“lorem”)>0”的帮助下检查特定关键字,如果单词存在,则返回true,然后您可以将类添加到body中,例如$(“body”).addClass(“ipsum”)

注:“lorem”-在url中找到的关键字/子字符串
“ipsum”-要添加到body中的类

关键字位于
窗口中。location.hash
。对此,您还需要知道什么?var hash=window.location.hash$('body').addClass(hash.replace('#','');始终要将哈希添加为类,还是只匹配某些哈希?