有序列表索引 [英] Ordered List Index
问题描述
有没有办法让 li
标签的数字(索引) >我试图获得侧面显示的号码(列表编号)。我知道传统的方法是使用存储行号的id,但这意味着如果在两行之间添加一行,很多id将不得不被编辑。尽管我为此开发了一种算法,但效率并不高。
我正在寻找一种在Javascript中使用的解决方案。
$ b $你可以使用
> previousElementSibling
一步一步地跳到列表的开始位置,并计算您所做的跳跃次数:
ol.onclick = function(e){
var li = e.target,
i = 1;
while(li.previousElementSibling){
li = li.previousElementSibling;
i + = 1;
}
alert('Index ='+ i);
};
请注意,元素遍历并未在IE8或更低版本中实现(但在IE9中) p>
现场演示: http:/ /jsfiddle.net/simevidas/U47wL/
如果您有开始
在OL元素上设置的属性,然后修改
i = ol.start || 1;
现场演示: http://jsfiddle.net/simevidas/U47wL/2/
如果您需要跨浏览器解决方案,那么您可以使用 previousSibling
,然后检查兄弟是否一个元素节点,然后只增加:
ol.onclick = function(e){
var e = e | | window.event,
li = e.target || e.srcElement,
i = ol.start || 1;
while(li.previousSibling){
li = li.previousSibling;
if(li.nodeType === 1){i + = 1; }
}
alert('Index ='+ i);
};
现场演示: http://jsfiddle.net/simevidas/U47wL/4/
jQuery解决方案:
$('ol')。click(function(e){
var n = $(e.target).index()+ this.start;
alert('Index ='+ n);
});
现场演示: http://jsfiddle.net/simevidas/U47wL/5/
Is there any way to get the number (index) of a li
tag in an ordered list?
I'm trying to get the number that is shown on the side (the list numbering). I know that the traditional way is to use an id which stores the line number but this would mean that if a line is added in between, a lot of ids would have to be edited. Even though I have developed an algorithm for this, it is not so efficient.
I'm looking for a solution to use in Javascript.
You can use previousElementSibling
to jump step-by-step to the beginning of the list and just count how many jumps you made:
ol.onclick = function(e) {
var li = e.target,
i = 1;
while ( li.previousElementSibling ) {
li = li.previousElementSibling;
i += 1;
}
alert( 'Index = ' + i );
};
Note that Element Traversal is not implemented in IE8 or below (but it is in IE9).
Live demo: http://jsfiddle.net/simevidas/U47wL/
If you have the start
attribute set on the OL element, then just modify the line where i
is declared do this:
i = ol.start || 1;
Live demo: http://jsfiddle.net/simevidas/U47wL/2/
If you require a cross-browser solution, then you can use previousSibling
and then check whether the sibling is an element node and only increment then:
ol.onclick = function(e) {
var e = e || window.event,
li = e.target || e.srcElement,
i = ol.start || 1;
while ( li.previousSibling ) {
li = li.previousSibling;
if ( li.nodeType === 1 ) { i += 1; }
}
alert( 'Index = ' + i );
};
Live demo: http://jsfiddle.net/simevidas/U47wL/4/
jQuery solution:
$('ol').click(function(e) {
var n = $(e.target).index() + this.start;
alert( 'Index = ' + n );
});
Live demo: http://jsfiddle.net/simevidas/U47wL/5/
这篇关于有序列表索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!