HTML / CSS:如何获取子菜单的ID

时间:2016-08-12 06:32:38

标签: jquery html css

如果我有一个带代码的index.html文件:

<li><a href="#">QA</a>
    <ul>
        <li><a href="1.html">current-status</a>
        </li>
        <li><a href="2.html">update status</a>
        </li>
    </ul>
</li>

当我点击此菜单时,我需要获取当前状态和更新状态的ID,这是QA的子菜单。

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
$(".main").click(function(){
   $(this).find("li").each(function() {
     console.log($(this).attr('id'))
   })
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="main"><a href="#">QA</a>
   <ul>
     <li id="current_status"><a href="1.html">current-status</a>
     </li>
     <li id="update_status"><a href="2.html">update status</a>
     </li>
   </ul>
</li>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

试试这个,用jQuery很容易

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
	
	
<li class="mainli">QA
   <ul>
	<li id="current">current</li>
	<li id="update">update</li>
   </ul>
</li>
	
</body>

<script type="text/javascript">
	$(document).ready(function(){
		$("li.mainli ul li").click(function(){//this line you call to the list element inside the mainli class then get the ul element and after that it gets li element 
			var theclickedId = $(this).attr("id");//in this line it takes the id value of the each item click by there user
			alert(theclickedId);
		});
	});
</script>
</html>

在评论中提到的问题的第二部分 这样做

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
	

		<li class="mainli">PUBLIC 
		  	<ul> 
		  	<li id="PUBLIC_current">current</li> 
		  	<li id="PUBLIC_update">update</li> 
		  	</ul> 
		</li> 
		<li class="mainli">DEV 
			<ul> 
			<li id="DEV_current1">current</li> 
			<li id="DEV_update1">update</li> 
			</ul> 
		</li>
	
</body>

<script type="text/javascript">
	$(document).ready(function(){
		$("li.mainli ul li").click(function(){
			
			var getmainId = $(this).attr("id")
			alert(getmainId);

		});
	});
</script>
</html>