【问题标题】:Jquery If something !=null, give 'else' true alsoJquery如果某事!= null,也给'else'真
【发布时间】: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


    【解决方案1】:

    您正在为每个 body 标签类运行 if-else 语句。所以,除非&lt;body&gt; 标签只有一个类,否则你总会找到一些不是title-* 的类。

    您应该修改您的代码,以便仅在 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');
    }
    

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

    【讨论】:

    • 一个月前开始学习JS。什么是“!找到”?像“!=”之类的东西?
    • 这是逻辑 not 运算符。 !found 等价于 found != false
    【解决方案2】:

    你可以只用 css 得到同样的结果

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

    【讨论】:

    • style1、style2等的变化太多了,所以jQuery是更好的解决方案。
    • 这就是你的意见;)我认为在页面加载后添加类名以进行样式设置很奇怪。但我很高兴你得到了修复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 2013-05-03
    • 2013-02-19
    • 1970-01-01
    相关资源
    最近更新 更多