[英]jQuery if else unordered list addClass
I have a ul
with four li
elements. 我有四个li
元素的ul
。 I want to check to see which one has the class .selected
. 我想检查一下哪个人选择了.selected
类。 If the li
hasClass .selected
, do nothing. 如果li
hasClass .selected
,则不执行任何操作。 If another .li
in the same list does NOT have the .selected
class, I want to add the class .li-border
. 如果同一列表中的另一个.li
没有.selected
类,我想添加.li-border
类。 In the code example below, I can get the console.log to fire but not the addClass. 在下面的代码示例中,我可以启动console.log,但不能启动addClass。 What am I missing? 我想念什么? Thanks! 谢谢!
if ($("ul.portfolio-nav li a").hasClass("selected")) {
console.log("yo");
} else {
$(this).addClass("li-border");
};
Try this code : 试试这个代码:
$("ul.portfolio-nav li a").each(function(){ if ( !$(this).hasClass("selected") ) { $(this).addClass("li-border"); }; });
.li-border{ border: 1px solid black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class='portfolio-nav'> <li><a href='#'>First element</a></li> <li><a href='#' class="selected">Second and selected element</a></li> <li><a href='#'>Third element</a></li> </ul>
Hope this helps. 希望这可以帮助。
The :not
selector should do the trick: :not
选择器应该可以解决问题:
$("ul.portfolio-nav li a:not(.selected)").addClass('li-border');
Or alternatively use the '.not' function, as suggested by jQuery documentation : 或使用jQuery文档建议的'.not'函数:
$("ul.portfolio-nav li a").not(".selected").addClass('li-border');
Don't over complicate yourself. 不要过度复杂化自己。 Just remove all li-border class then add it to the one set you want to match too. 只需删除所有li-border类,然后将其也添加到您要匹配的一组中即可。
https://jsfiddle.net/da98dmgt/7/ https://jsfiddle.net/da98dmgt/7/
$("ul.portfolio-nav li").click(function(){
$("ul.portfolio-nav ul li").removeClass("li-border");
$(this).siblings("li").addClass("li-border");
});
Here's an example. 这是一个例子。 It should be easy to replace the styles with the one you want. 用所需的样式替换样式应该很容易。
$(document).ready(function() { $("#list-items li").each(function() { if (!$(this).hasClass('selected')) { $(this).addClass('disable'); } }); });
li:hover, .selected { text-decoration: underline; cursor: pointer; color: black; } .disable { color: gray; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <ul id="list-items"> <li>List item</li> <li>List item</li> <li class="selected">Selected item</li> <li>List item</li> </ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.