<ul>
<li>a</li>
<li>b</li>
<li>c</li>
</ul>当点击一个LI的时候,怎么知道这个是第二个还是第三个子?
要求:不要给每个LI加上“id=1”之类的东西。最好可以用Jquery里面的方法来实现。
<li>a</li>
<li>b</li>
<li>c</li>
</ul>当点击一个LI的时候,怎么知道这个是第二个还是第三个子?
要求:不要给每个LI加上“id=1”之类的东西。最好可以用Jquery里面的方法来实现。
$("ul>li").click(function(){
var $allLi=$("ul>li");
//console.log($allLi.index($(this))+1);
alert($allLi.index($(this))+1);
});
});
<ul>
<li onclick='getP(this)'>a </li>
<li onclick='getP(this)'>b </li>
<li onclick='getP(this)'>c </li>
<li onclick='getP(this)'>d </li>
<li onclick='getP(this)'>e </li>
</ul>
<script type='text/javascript'>
var getP = function(o){
var i = 0;
while(o = o.previousSibling ){
if(o.nodeName!='#text') i++;
}
alert(i);
}
</script>
$("ul>li").click(function(){
alert($("ul>li").index(this));
});
});
index( Element subject ) returns Number
Searches every matched element for the object and returns the index of the element, if found, starting with zero.
Returns -1 if the object wasn't found.Example:
On click, returns the index (based zero) of that div in the page.
$("div").click(function () {
// this is the dom element clicked
var index = $("div").index(this);
$("span").text("That was div index #" + index);
});
HTML:
<span>Click a div!</span>
<div>First div</div>
<div>Second div</div>
<div>Third div</div>
<!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 runat="server">
<title></title>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() { $("ul li").click(function() { alert("你点击的是第" + $("ul li").index($(this)) + "个"); alert($(this).html()) }); })</script>
</head>
<body>
<ul>
<li>a </li>
<li>b </li>
<li>c </li>
</ul>
</body>
</html>
判断当前点的是哪个节点
<div class="mainChild">1</div>
<div class="mainChild">2</div>
<div class="mainChild">3</div>
<div class="mainChild">4</div>
<div class="mainChild">5</div></div>
$(function() {
$(".mainChild").click(function() {
var dd = $(".mainChild").index($(this));
setbg(dd);
});
});