如何在body标签上添加一个类? [英] How to add a class to body tag?

查看:213
本文介绍了如何在body标签上添加一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jQuery将类添加到body标签.

I want to add a class to a body tag with jQuery.

例如,如果URL为 http://www.mywebsite.com/about_us.asp,我想将前五个字母(在本例中为约")添加到body标签:

For example if the URL is http://www.mywebsite.com/about_us.asp, I want add the first five letters, in this case 'about', to the body tag:

<body class="about">

我该怎么做?

推荐答案

这应该做到:

var newClass = window.location.href;
newClass = newClass.substring(newClass.lastIndexOf('/')+1, 5);
$('body').addClass(newClass);

整个五个字符"有点令人担忧;这种任意截止通常是一个危险信号.我建议捕获所有内容,直到_或.:

The whole "five characters" thing is a little worrisome; that kind of arbitrary cutoff is usually a red flag. I'd recommend catching everything until an _ or .:

newClass = newClass.match(/\/[^\/]+(_|\.)[^\/]+$/);

该模式应产生以下内容:

That pattern should yield the following:

  • ../about_us.html:关于
  • ../something.html:某事
  • ../has_two_underscores.html:具有
  • ../about_us.html : about
  • ../something.html : something
  • ../has_two_underscores.html : has

这篇关于如何在body标签上添加一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆