简体   繁体   English

如何设置此条件? (Jquery的/ JavaScript的)

[英]how can I set this conditions? (Jquery/javascript)

thanks for your time and first of all I'm a noobie who's been learning by his own javascript so I don't manage quite good the selectors to achieve what I want. 感谢您的时间,首先,我是一个Noobie,他一直在用自己的JavaScript学习,因此我无法很好地控制选择器来实现我想要的功能。 Here it's my problem: 这是我的问题:

html 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 CSS

.highlighted{
    color: red;
}

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

.match_group{
    border: 1px solid black;    
}

Look here pelase: * http://jsfiddle.net/nero_noob_123/ctcn7kfy/2/ 看这里pelase:* http://jsfiddle.net/nero_noob_123/ctcn7kfy/2/

basically what I want to achieve with the jquery and javascript it's the following.... but I don't know how write it as a condition so try to read it as follows: 基本上,我想用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

    }

I hope I have made myself clear, and sorry that's the best I can do with my current knowledge in JQ and javascript 希望我已经说清楚了,很抱歉,根据目前对JQ和javascript的了解,这是我能做的最好的事情

PD: feel free to modify the crapy code I wrote to acheive what I need, thank you! PD:随时修改我编写的简短代码以实现我的需要,谢谢!

You can pass a second parameter to toggleClass that will turn on or off the specified class. 您可以将第二个参数传递给toggleClass ,以打开或关闭指定的类。 https://api.jquery.com/toggleClass/ https://api.jquery.com/toggleClass/

That can be a boolean value, or (and this does not appear to be documented) it can be a function returning a boolean result! 那可以是一个布尔值, 或者 (并且似乎没有记载)它可以是一个返回布尔结果的函数!

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM