Javascript 获取li的索引有一个类,没有另一个类
我有下面的代码来查找li的索引,该索引具有类Javascript 获取li的索引有一个类,没有另一个类,javascript,jquery,Javascript,Jquery,我有下面的代码来查找li的索引,该索引具有类活动和不具有隐藏类。为了找到值,我们不想计算隐藏的类 var index=$('li')。非('.hidden')。查找('.active')。索引(); 警报(索引) 您可以使用,它在同一级别上搜索匹配元素的子集,其中as.find()查找子元素 var index = $('li').not('.hidden').filter('.active').index(); 或者,可以根据需要进行改进 var index = $('l
活动
和不具有隐藏
类。为了找到值,我们不想计算隐藏的类
var index=$('li')。非('.hidden')。查找('.active')。索引();
警报(索引)
您可以使用,它在同一级别上搜索匹配元素的子集,其中as.find()
查找子元素
var index = $('li').not('.hidden').filter('.active').index();
或者,可以根据需要进行改进
var index = $('li.active:not(.hidden)').index();
如果需要排除.hidden
,则需要从无序列表中删除它们,然后可以使用.index()
var index = $('ul').clone().find('li.hidden').remove().end().find('li.active').index();
var index=$('ul').clone().find('.hidden').remove().end().find('li.active').index();
console.log(索引)
- 隐藏
- 隐藏
- 活动
- 隐藏
使用ul代替li
var index = $('ul').not('.hidden').find('.active').index();
alert(index)
虽然您在撰写本文时已经接受了另一个答案,但我认为我应该提供一种替代方法,使用纯JavaScript来实现同样的目的(尽管有进一步、简单、定制的选项):
函数findIndexOf(opts){
让设置={
“针”:“活动”,
‘草垛’:‘ulli’,
“忽略”:“隐藏”,
“第一间接”:对
};
Object.keys(opts |{}).forEach(function(key){
设置[键]=选择[键];
});
让lis=Array.from(document.queryselectoral(settings.haystack)),
notignered=lis.filter(el=>el.classList.contains(settings.ignered)==false),
索引=不忽略.map(函数(el,索引){
if(el.classList.contains(settings.needle)){
收益指数;
}
}).filter(值=>value);
如果(index.length==0){
指数推升(-1);
}
返回设置。firstIndexOnly==真?[索引[0]]:索引;
}
let found=findIndexOf(),
prepend=found.length==1?“索引:':'索引:';
log(prepend+JSON.stringify(find))代码>
li{
高度:2米;
线高:2米;
边框:1px纯色;
保证金:0.5em0;
列表样式类型:无;
}
.隐藏{
颜色:#f90;
宽度:80%;
不透明度:0.6;
}
.主动{
颜色:柠檬黄;
宽度:50%;
}
李:以前{
内容:attr(类);
显示:内联块;
文本缩进:1em;
}
我在您的示例中添加了一个fiddle,只有一个在激活之前不隐藏类,但这返回3是的,这正是我想要的。您试图精确计算的是什么?位置为.active,位置为exclude.hidden
// using a named function allows you to call that function
// repeatedly in response to interaction or other events:
function findIndexOf(opts) {
// setting the 'default' settings of the function,
// these defaults can be overridden by the user:
// 'needle': String, the class-name of the element(s)
// whose index/indices you wish to find.
// 'haystack': String, the CSS selector for those elements
// from which you expect to find the 'needle(s).'
// 'disregard': String, the class-name of those elements in
// the haystack you wish to disregard from the
// index 'count.'
// 'firstIndexOnly' : Boolean, true - return only the index of the
// first needle found;
// false - return the indices of all
// found needles.
let settings = {
'needle': 'active',
'haystack': 'ul li',
'disregard': 'hidden',
'firstIndexOnly': true
};
// Using Array.prototype.forEach() to iterate over the
// array of keys returned from Object.keys, of either
// the 'opts' Object (supplied by the user to override
// the default settings), or an empty Object to prevent
// errors being thrown if the opts Object doesn't exist:
Object.keys(opts || {}).forEach(function(key) {
// 'key' is supplied the anonymous function,
// and refers to the current key of the array
// over which we're iterating.
// here we update the settings[key] with the value of
// opts[key]:
settings[key] = opts[key];
});
// Using Array.from() to convert the NodeList returned by
// document.querySelectorAll( settings.haystack ) into an
// Array, in order to employ Array methods on that collection:
let lis = Array.from(document.querySelectorAll(settings.haystack)),
// here we use Array.prototype.filter(), with an Arrow
// function syntax, to retain only those elements
// whose classList does not contain the class identified
// by the settings.disregard option, thereby removing the
// options to be disregarded from the collection:
notDisregarded = lis.filter(el => el.classList.contains(settings.disregard) === false),
// iterating over the NotHiddenLis Array with
// Array.prototype.map(), to obtain the indices of
// those elements matching the class-name supplied
// by the settings.needle option:
indices = notDisregarded.map(function(el, index) {
// Again, the arguments here are supplied by the
// anonymous function though the names are chosen
// by the user, the first argument (here 'el')
// is the array element of the Array over which
// we're iterating; 'index' (the second argument)
// is the index of that current array element.
// element.classList.contains() returns a Boolean
// true, if the class-name supplied is found within
// the classList of the element; or false if it is
// not found.
if (el.classList.contains(settings.needle)) {
// if the element has the supplied class-name
// (the string held in the settings.needle variable)
// el.classList.contains() evaluates to true, and then
// we return the associated index:
return index;
}
// because the above approach returns undefined (when the
// element.classList.contains() returns false) we here use
// Array.prototype.filter(), with an Arrow function, to
// retain only those array-elements that hold a value:
}).filter(value => value);
// to ensure we behave similarly to Array.prototype.indexOf(),
// and String.prototype.indexOf(), we check the length of
// the array of found indices and, if no elements were found,
// and therefore no indices were retained, we push the value of
// -1 into the array:
if (indices.length === 0) {
indices.push(-1);
}
// if the the settings.firstIndexOnly option is set to true,
// we return an array consisting of only the first array-element
// from the indices array, otherwise we return the whole array
// (whether that array contains only one value or multiple).
// We wrap the first array-value within an array in order to
// provide consistency in the returned values, so that the
// function always returns an Array:
return settings.firstIndexOnly === true ? [indices[0]] : indices;
}
// Almost entirely irrelevant, this is just to tidy the
// console/snippet output:
let found = findIndexOf(),
prepend = found.length === 1 ? 'Index: ' : 'Indices: ';
// showing the output of the function in the snippet.log
// (with thanks to T.J. Crowder):
snippet.log(prepend + JSON.stringify(found) );