17-解决方案
3.4.2 解决方案
当单击一个元素时,可以使用核心方法 index() 搜索整个选择集,了解该元素的索引:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>Chapter 3 - Recipe 4 - Getting the index of an item in a selection</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
<!--
(function($){
$(document).ready(function(){
$("div").click(function() {
alert("You clicked on div with an index of " +
$("div").index(this));
});
});
})(jQuery);
//-->
</script>
</head>
<body>
<div>click me</div>
<div class="test">test</div>
<div>click me</div>
</body>
</html>
从绑定所有 <div> 元素的单击事件开始。当单击 <div> 时,可以搜索相同选择集中的元素找出单击的是哪一个 <div>:$("div").index(this); ,其中的 this 是单击的 <div> 。