我想用jQuery向body标签添加一个类.
例如,如果URL是http://www.mywebsite.com/about_us.asp,我想在body标签中添加前五个字母,在本例中为"about":
<body class="about">
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
Rex*_*x M 45
这应该这样做:
var newClass = window.location.href;
newClass = newClass.substring(newClass.lastIndexOf('/')+1, 5);
$('body').addClass(newClass);
Run Code Online (Sandbox Code Playgroud)
整个"五个字"的东西有点令人担忧; 那种任意截止通常是一个红旗.我建议捕捉所有内容,直到_或.:
newClass = newClass.match(/\/[^\/]+(_|\.)[^\/]+$/);
Run Code Online (Sandbox Code Playgroud)
该模式应该产生以下结果:
../about_us.html
: 关于../something.html
:某事./has_two_underscores.html
: 具有