【发布时间】:2013-04-28 10:19:13
【问题描述】:
我需要从以 "title-" 开头的 body 标记中获取类名,然后将该类后缀添加到具有类 "title" 的 H1 中。如果没有前缀为“title-”的类,H1 应该有类“style-default”。
"title-style1" - 这个body类改变了它的后缀(style1),并且也放在了数组中,所以计算顺序无济于事。
<body class="first something title-style1 last">
<h2 class="title"> John Doe</h2>
<!-- need to get this:-->
<h2 class="title style1"> John Doe</h2>
<!-- but I'mg getting this:-->
<h2 class="title style1 style-default"> John Doe</h2>
<!-- this is just some other title-->
<h2 class="style2"> John Malkovich</h2>
</body>
我设法获得了想要的后缀,但无法正确放置“样式默认”。可能是一些“if else”错误。
$(document).ready(function(){
var classes = $("body").attr('class').split(' ');
for (var i = 0; i < classes.length; i++) {
// finding classes starting with title-
var $matches = /^title\-(.+)/.exec(classes[i]);
if ($matches != null) {
$sufix = $matches[1];
$(".title").addClass($sufix);
}
else {
// this also add class to every match ?
$('.title').addClass('style-default');
}
}
});
这是一个小提琴 http://jsfiddle.net/lima_fil/xz9bA/60/
谢谢
【问题讨论】:
标签: jquery class if-statement prefix