Jquery如果有什么=空,给出';其他';同样如此

Jquery如果有什么=空,给出';其他';同样如此,jquery,class,if-statement,prefix,Jquery,Class,If Statement,Prefix,我需要从以“title-”开头的body标记中获取类名,然后将该类后缀添加到具有类“title”的H1中。如果没有前缀为“title-”的类,H1应该具有类“style default” “title-style1”-这个body类更改了它的后缀(style1),并将其放置在数组中,所以计算顺序并没有帮助 <body class="first something title-style1 last"> <h2 class="title"> John Doe&l

我需要从以“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>  

无名氏
无名氏
无名氏
约翰·马尔科维奇
我设法得到了想要的后缀,但无法正确地放置“样式默认”。可能是“如果其他”的错误

$(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');
        }
    }
});
$(文档).ready(函数(){
变量类=$(“主体”).attr('class').split('');
对于(var i=0;i
这是一把小提琴


谢谢

您只需使用css即可获得相同的结果

<style>
body.style-style1 h1 {
    color: white;
}
body.style-style2 h1 {
    color: red;
}
</style>

body.style-style1 h1{
颜色:白色;
}
body.style-style2 h1{
颜色:红色;
}

您正在为每个类别的body标记运行
if-else
语句。所以,除非
标记只有一个类,否则您总会发现一些类不是
标题-*

您应该修改代码,以便仅在
for
循环之后添加
style default
类。大概是这样的:

var found = false;
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);

        found = true;
        break;
    }
}

if (!found) {
    $('.title').addClass('style-default');
}
var-found=false;
对于(var i=0;i

另外,请记住,以
$
开头的变量通常表示jQuery对象。(可能您混淆了PHP和JS?

样式1、样式2等的变体太多了,所以jQuery是更好的解决方案。这是您的观点;)我认为在页面加载后添加类名用于样式设计是很奇怪的。但我很高兴你找到了解决办法!我一个月前开始学习JS。什么是“发现”?类似于“!=”?它是逻辑
而不是
运算符<代码>!找到的
相当于找到的
错误