【问题标题】:how can I set this conditions? (Jquery/javascript)我该如何设置这个条件? (jQuery/javascript)
【发布时间】:2015-05-09 22:02:54
【问题描述】:

感谢您抽出宝贵时间,首先,我是一个通过自己的 javascript 学习的菜鸟,所以我不能很好地管理选择器来实现我想要的。这是我的问题:

html

<ul id='stuff' class='goods'>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li><span class='highlighted'>list item 4</span></li>
<li>list item 5</li>
</ul>

<ul id='stuff2' class='goods'>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>item 4</li>
<li>list item 5</li>
</ul>

CSS

.highlighted{
    color: red;
}

.goods{
    border:1px solid red;
    cursor: pointer; 
    padding: 0px;
    list-style: none;   
}

.match_group{
    border: 1px solid black;    
}

请看这里:* http://jsfiddle.net/nero_noob_123/ctcn7kfy/2/

基本上我想用 jquery 和 javascript 实现的功能如下....但我不知道如何将其写为条件,因此请尝试按如下方式阅读:

$('#stuff2').addClass('match_group');

$('#stuff2').addClass('match_group');

if($('li').has('span.highlighted').length){ //so span exist!
        $('span.highlighted').closest('.goods').addClass('match_group');
    }else if($('.goods').hasClass('match_group') && // span.highlight DOESN'T EXIST inside .goods) { 
/// remove the match_group class from '.goods' where span.highlight doesn't exist
    }else{ if any of the '.goods' classes has span.highlighted inside them, don not apply .match_group

    }

我希望我已经说清楚了,抱歉,这是我目前在 JQ 和 javascript 方面的知识所能做的最好的事情

PD:随意修改我写的蹩脚的代码来实现我的需要,谢谢!

【问题讨论】:

  • 为什么不直接:$('.goods').has('span.highlighted').addClass('match_group');

标签: javascript jquery jquery-selectors conditional


【解决方案1】:

您可以将第二个参数传递给toggleClass,它将打开或关闭指定的类。 https://api.jquery.com/toggleClass/

这可以是一个布尔值,(这似乎没有记录在案)它可以是一个返回布尔结果的函数!

$('.goods').toggleClass('match_group', function() {return $(this).has("span.highlighted");});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/ctcn7kfy/4/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 2014-05-10
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多