[英]jQuery loop find last data attribute with a value of true and add class
I have the following loop that selects each accordion element on the page and checks if the data attribute is true (each accordion element is a step in a process), if the data attribute is true the active class is applied and the accordion is expanded. 我有以下循环,它选择页面上的每个手风琴元素并检查data属性是否为true(每个手风琴元素是流程中的一个步骤),如果data属性为true,则将应用活动类并扩展手风琴。 However, I would like to apply the active class to the last element with the data attribute of true only. 但是,我想将活动类应用于仅具有data属性为true的最后一个元素。
jQuery: jQuery的:
var $steps = $('dd.accordion-navigation.workspace-step');
$steps.each(function () {
var stepComplete = $(this).data('workspace-step-complete');
if (stepComplete === true) {
$(this).addClass('active')
.find('.content')
.addClass('active');
}
});
HTML: HTML:
<dd class="accordion-navigation workspace-step" data-workspace-step-complete="true">
<!-- Apply active class to this step only -->
<dd class="accordion-navigation workspace-step" data-workspace-step-complete="true">
<dd class="accordion-navigation workspace-step" data-workspace-step-complete="false">
<dd class="accordion-navigation workspace-step" data-workspace-step-complete="false">
<dd class="accordion-navigation workspace-step" data-workspace-step-complete="false">
Try using attribute equals selector , :last
selector .is()
尝试使用属性等于选择器, :last
选择器.is()
var $steps = $('dd.accordion-navigation.workspace-step');
$steps.each(function () {
$(this).is("[data-workspace-step-complete=true]:last") &&
$(this).addClass('active')
.find('.content')
.addClass('active');
});
You should get the attribute 'data-workspace-step-complete' using attr
function and then check if value is true and perform respective operation. 您应该使用attr
函数获取属性“ data-workspace-step-complete”,然后检查value是否为true并执行相应的操作。
var $steps = $('.accordion-navigation.workspace-step');
var i = -1;
$steps.each(function () {
var stepComplete = $(this).attr("data-workspace-step-complete");
if (stepComplete == "true") {
i++;
}
});
i
would now give you the index of last element with attr = "true". i
现在将为您提供attr =“ true”的最后一个元素的索引。
var LastElementwithTrue = $('.accordion-navigation.workspace-step').eq(1);
.last()方法应针对所需的元素:
$('[data-workspace-step-complete=true]').last().addClass('active')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.