<!DOCTYPE html>
<html>
<head>
<title>jQuery Accordion Menu Demo</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="main.js" type="text/javascript"></script>
</head>
<body>
<div id='menu'>
<ul>
<li> <a href='#'><span id="Science">Science</span></a>
<ul>
<li><a href='#'>Mathematics</a></li>
<li><a href='#'>Physics</a></li>
<li><a href='#'>Chemistry</a></li>
</ul>
</li>
</ul>
</div>
<script>
$('#menu li>ul>li').click(function() {
alert(span id is Science);
});
</script>
</body>
</html>
这是我正在尝试做的代码。
我希望当用户点击数学、物理或化学时,它应该使用 JQuery 在 ALERT 中显示 parent 的 SPAN ID。
最佳答案
你可以使用关系
$('#menu li>ul>li').click(function() {
var id = $(this)
.parent() //Travese up to UL
.closest('li') //Travese up to li
.find('span') //Finds the span
.attr('id'); //Fetches the id attribute
alert('span id is: ' + id);
});
$(function() {
$('#menu li>ul>li').click(function() {
var id = $(this)
.parent() //Travese up to UL
.closest('li') //Travese up to li
.find('span') //Finds the span
.attr('id'); //Fetches the id attribute
alert('span id is: ' + id);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='menu'>
<ul>
<li> <a href='#'><span id="Science">Science</span></a>
<ul>
<li><a href='#'>Mathematics</a>
</li>
<li><a href='#'>Physics</a>
</li>
<li><a href='#'>Chemistry</a>
</li>
</ul>
</li>
</ul>
</div>
关于javascript - 当我单击元素数学/物理/化学时如何使用 jquery 获取跨度 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34986970/