我有以下 html 代码。我想在此代码中选择奇数或偶数 .menu-item ul 元素,它们以无限嵌套格式放置。请帮助我...
<nav class='amazing-menu '>
<ul id='menu_container'>
<li class="parent">
<a href="#" class="link">First</a>
<div class="sub-menu">
<ul class="menu-item">
<!-- I want to => background-color: red; -->
<li>
<a href="" class="link">sub-item1</a>
</li>
<li class="parent">
<a href="" class="link">sub-item1</a>
<div class="sub-menu">
<ul class="menu-item">
<!-- I want to => background-color: blue; -->
<li><a href="link">sub-sub-item1</a>
</li>
<li><a href="link">sub-sub-item2</a>
</li>
<li><a href="link">sub-sub-item3</a>
</li>
<li class="parent"><a href="link">sub-sub-item4</a>
<div class="sub-menu">
<ul class="menu-item">
<!-- I want to => background-color: green; AND so on ... -->
<li><a href="link">sub-sub-sub-item1</a>
</li>
<li><a href="link">sub-sub-sub-item2</a>
</li>
<li><a href="link">sub-sub-sub-item3</a>
</li>
<li><a href="link">sub-sub-sub-item4</a>
</li>
</ul>
</div>
</li>
<li><a href="link">sub-sub-item2</a>
</li>
<li><a href="link">sub-sub-item3</a>
</li>
</ul>
</div>
</li>
<li>
<a href="" class="link">sub-item2</a>
</li>
</ul>
</div>
</li>
</ul>
</nav>
好了,根据我的理解,您应该没问题。如果应该在 li 的 item-menu
中完成工作,请使用评论中的方法!希望它符合您的目标。
</style>
</head>
<body>
<nav class='amazing-menu '>
<ul id='menu_container'>
<li class="parent">
<a href="#" class="link">First</a>
<div class="sub-menu">
<ul class="menu-item">
<!-- I want to => background-color: red; -->
<li>
<a href="" class="link">sub-item1</a>
</li>
<li class="parent">
<a href="" class="link">sub-item1</a>
<div class="sub-menu">
<ul class="menu-item">
<!-- I want to => background-color: blue; -->
<li><a href="link">sub-sub-item1</a>
</li>
<li><a href="link">sub-sub-item2</a>
</li>
<li><a href="link">sub-sub-item3</a>
</li>
<li class="parent"><a href="link">sub-sub-item4</a>
<div class="sub-menu">
<ul class="menu-item">
<!-- I want to => background-color: green; AND so on ... -->
<li><a href="link">sub-sub-sub-item1</a>
</li>
<li><a href="link">sub-sub-sub-item2</a>
</li>
<li><a href="link">sub-sub-sub-item3</a>
</li>
<li><a href="link">sub-sub-sub-item4</a>
</li>
</ul>
</div>
</li>
<li><a href="link">sub-sub-item2</a>
</li>
<li><a href="link">sub-sub-item3</a>
</li>
</ul>
</div>
</li>
<li>
<a href="" class="link">sub-item2</a>
</li>
</ul>
</div>
</li>
</ul>
</nav>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementsByClassName("sub-menu");
for(var i = 0; i<x.length; i++)
{
if(i%2==0)
{
document.getElementsByClassName("menu-item")[i].style.backgroundColor = "red";
}
else
{
document.getElementsByClassName("menu-item")[i].style.backgroundColor = "blue";
}
}
}
</script>
</body>
</html>
附言我把图片放在这里,你可以看看是否符合你的要求! https://s27.postimg.org/ta75cv36r/image.png
我是一名优秀的程序员,十分优秀!