我想使用jQuery添加一个body到body标签的类。
例如,如果URL为http://www.mywebsite.com/about_us.asp,我想将前五个字母(在本例中为“about”)添加到body标签中:
<body class="about">
我怎样才能做到这一点?
解决方法
这应该做:
var newClass = window.location.href; newClass = newClass.substring(newClass.lastIndexOf('/')+1,5); $('body').addClass(newClass);
整个“五字”的事情有点令人担忧;这种任意截断通常是红旗。我建议抓住一切,直到_或。:
newClass = newClass.match(/\/[^\/]+(_|\.)[^\/]+$/);
该模式应该产生以下结果:
> ../about_us.html:关于> ../something.html:某事> ../has_two_underscores.html:has