可以使用JavaScript获取列表项(< li>)标签? [英] Possible to get list item (<li>) label with JavaScript?
问题描述
如果我有一个 ul
,其中有3个项目,并且列表样式类型
已设置到 lower-alpha
,我最终得到这个
If I've got a ul
with 3 items in it and the list-style-type
is set to lower-alpha
, I end up with this
a。项目1
a. Item 1
b。项目2
c。项目3
使用jQuery,我可以轻松获取点击的任何项目的值 - 项目1,如果我点击第一个。但是我可以得到列表项标签吗?在这种情况下, a ?
With jQuery, I can easily get the value of any item you click - "Item 1" if I click the first. But can I get the list item label? In this case a?
推荐答案
不知道DOM API是否公开,但是你可以...
Not sure if the DOM API exposes that, but you could do...
$('ul').on('click', 'li', function() {
var label = String.fromCharCode(97 + $(this).index());
});
...如果您<26> 下有元素。如果你有更多的话,你将需要使用一个更为复杂的算法,通常被称为Excel行到列算法。
...if you had under 26 elements. If you have more, you would need to use a more complicated algorithm, typically known as the Excel Row to Column algorithm.
$('ul').on('click', 'li', function() {
var index = $(this).index() + 1;
var label = '';
var mod;
while (index) {
mod = (index - 1) % 26;
label = String.fromCharCode(97 + mod) + label;
index = Math.floor((index - mod) / 26);
}
});
这篇关于可以使用JavaScript获取列表项(< li>)标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!