![](/img/trans.png)
[英]Loop through all elements with class name 'blah' in jquery and use the contents of the element in a function
[英]jQuery function to loop through elements and set class names based on order compared to an element with a specific class name
当前的Codepen: http ://codepen.io/anon/pen/rVNpvg
function opcWizardry() { var $activeBox = $('.box.active'); $activeBox.prevAll('.box').addClass('done'); $activeBox.nextAll('.box').addClass('hidden'); } opcWizardry();
.box { border: solid 1px #bbb; margin: 5px; padding: 5px; } .box.done { background: #bbb; } .box.active { background: green; } .box.hidden { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box">box1</div> <div class="box">box2</div> <div class="box active">box3</div> <div class="box">box4</div> <div class="box">box5</div>
我目前正在研究做到这一点的最佳方法,并且很乐意输入。
我正在编写一个函数,该函数将遍历具有class名称为box的这组元素。 该列表中的元素之一的类名称为active 。 对于活动类之前的所有元素,我想将类名称设置为done 。 对于活动类之后的所有元素,我想将类名设置为hidden 。
我这样做的方式似乎不必要地重复,而且我想知道是否有人可以提供一种优雅的方法。
var $activeBox = $('.box.active');
$activeBox.prevAll('.box').addClass('done');
$activeBox.nextAll('.box').addClass('hidden');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.