jquery addclass 如果某些数量的 li 有类
如果一组 li 应用了特定的类,我正在尝试向跨度添加一个类。
李.完整的
丽丽
。完整的
丽丽
。完整
等...
span #完成
如果 4 个 li 具有“完整”类,则我尝试向跨度添加“活动”类 我已经尝试了以下操作,我可以让 click 事件起作用,但不能让 if 语句起作用,这是否可能或有效?
$(function(){
$("li").click(function(){
$(this).addClass("complete");
});
if($("li").hasClass("complete")){
$("#done").addClass("active");
};
});
我一直在寻找一种方法来计算 li.complete 在 dom 中的数量,然后针对它添加 Class,但运气不佳,
谢谢
I am attempting to add a class to a span, if a set of li's have a specific class applied to them.
li . complete
li
li . complete
li
li . complete
etc...
span # done
I was attempting to add a class of "active" to the span if 4 of the li's have the class "complete"
I've tried the following, and I can get the click event to work but not the if statement, and is this even possible or efficiient?
$(function(){
$("li").click(function(){
$(this).addClass("complete");
});
if($("li").hasClass("complete")){
$("#done").addClass("active");
};
});
Ive been digging for a way to maybe count the li.complete's withing the dom then addClass against it but haven't had much luck
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您当前的代码不会有两个问题:您
在绑定
click()
处理程序后立即运行,而不是在实际单击按钮后运行。此外,您没有计算已完成的li
数量。一种选择是,每次处理点击时,计算类完成时的
li
数量:您也可以随时保持运行计数...
但如果您愿意的话能够取消选择项目,这会使您的代码更加复杂。
Your current code won't has two problems: you're running
immediately after binding the
click()
handler, not after the button has actually been clicked. Additionally, you're not counting the number ofli
s that have been made complete.One option is this, counting the number of
li
's with the class complete each time you handle the click:You could also keep a running count as you go...
but if you ever want to be able to unselect items, this would make your code more complicated.
试试这个:
Try this:
如果我正确理解了您的问题,并且您想要将一个类应用于一个元素(如果 4 个
li
元素都具有特定的类),您可以执行以下操作:查看其工作示例 这里。
If I've understood your question correctly, and you want to apply a class to an element if 4
li
elements all have a specific class, you can do this:See an example of it working here.
您可以计算具有完整选择器的所有
li
元素,并查看计数是否至少为 4:You could count all of the
li
elements that have your complete selector and see if the count is at least 4: