Javascript 单击时显示第n个子编号-将第n个子编号转换为变量
我需要一个javascript来显示我点击li时的第n个子编号。 例如,如果我单击“apple”console.log,则显示“2”。 我想把第n个子数变成一个变量Javascript 单击时显示第n个子编号-将第n个子编号转换为变量,javascript,variables,css-selectors,click,show,Javascript,Variables,Css Selectors,Click,Show,我需要一个javascript来显示我点击li时的第n个子编号。 例如,如果我单击“apple”console.log,则显示“2”。 我想把第n个子数变成一个变量 <!DOCTYPE html> <html> <head> <style type="text/css"> li:nth-child(1) b {color: #eeaa33;} li:nth-child(2) b
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
li:nth-child(1) b {color: #eeaa33;}
li:nth-child(2) b {color: #0000ff;}
li:nth-child(3) b {color: #ff3300;}
</style>
</head>
<body>
<ul class="menu">
<li><b>apple</b></li>
<li><b>watermelon</b></li>
<li><b>blueberry</b></li>
</ul>
<script>
//I need a javascript to show me the nth-child number when I click a li.
//For example if I click "apple" console.log show me "2".
// I want to turn nth-child number into a variable.
</script>
</body>
</html>
李:第n个孩子(1)b{color:#eeaa33;}
李:第n个孩子(2)b{color:#0000ff;}
李:第n个孩子(3)b{color:#ff3300;}
- 苹果
- 西瓜
- 蓝莓
//我需要一个javascript来显示我点击li时的第n个子编号。
//例如,如果我单击“apple”console.log,则显示“2”。
//我想把第n个子数变成一个变量。
如果您可以使用jQuery,这会有所帮助。将单击处理程序分配给“li”,对单击的元素调用.prevAll(),并获取结果集的长度以获取单击元素之前的同级数。添加1,使第一个li具有n=1
$("li").click(function(){
var n = $(this).prevAll().length + 1;
console.log(n);
});
谢谢你的回答,但它不起作用。你知道一种使用纯javascript的方法吗?嗯,这对我很有用。好吧,关于你问题的“可能重复”评论有一些纯JS的解决方案。