我想知道无序列表中单击的li元素的索引。如何用jQuery实现这个目标?
答案 0 :(得分:3)
$('ul li').on('click', function(ev) {
var index = $(this).index();
});
答案 1 :(得分:2)
$( 'li' ).on( 'click', function() {
$( this ).index()
} )
答案 2 :(得分:2)
<head>
<style>
div { background:yellow; margin:5px; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<span>Click a div!</span>
<div>First div</div>
<div>Second div</div>
<div>Third div</div>
<script>
$("div").click(function () {
// this is the dom element clicked
var index = $("div").index(this);
$("span").text("That was div index #" + index);
});
</script>
</body>
</html>
来自Jquery Api的代码
答案 3 :(得分:0)
这样做: -
$('li').click(function() {
alert($(this).index());
});