使用罗马数字假定以下html中的有序列表
<ol type="I">
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
<li value="1984">big brother</li>
</ol>
哪个呈现为:
I. one
II. two
III. three
IV. four
MCMLXXXIV. big brother
在给定任意元素的情况下,是否有一种方法可以从其属性中提取用作该元素前缀的字符串?
例如,给定第四个元素,我可以做些什么来获取字符串IV
吗?还是给定最后一个元素,得到字符串MCMLXXXIV
?
答案 0 :(得分:0)
您需要编写一个romanize函数。如果我正确理解您的问题。
将列表项的索引作为值或数据元素会有所帮助。
$("li").each(function(){
if ($(this).text() === 'big brother') {
alert(romanize($(this).val()));
}
});
function romanize (num) {
if (isNaN(num))
return NaN;
var digits = String(+num).split(""),
key = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
"","I","II","III","IV","V","VI","VII","VIII","IX"],
roman = "",
i = 3;
while (i--)
roman = (key[+digits.pop() + (i * 10)] || "") + roman;
return Array(+digits.join("") + 1).join("M") + roman;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol type="I">
<li value="1">one</li>
<li value="2">two</li>
<li value="3">three</li>
<li value="4">four</li>
<li value="1984">big brother</li>
</ol>