获取当前的 li 是第几个要怎么写 鼠标经过li 提示 在第几? javascript 高手来

如题所述

这,需要借助dom的相关知识。可能需要遍历父元素的子元素来完成li的定位,不过效率可能不高。
给个例子,第一访问的时候缓存li的序列,需要一些辅助的属性和空间:

<!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>无标题文档</title>
</head>

<body>

<ul id="L_List">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
<div id="P_Index"></div>
<script type="text/javascript">
document.getElementById("L_List").onmouseover=function(e){
var o=e?e.target:event.srcElement;
if(o.tagName=="LI"){
if(o["index"]== undefined){
var ul=o.parentNode;
var liList = ul.getElementsByTagName("li");
for(var i=0,li;li=liList[i];++i)
li["index"]=i;
}
document.getElementById("P_Index").innerHTML=o["index"];
}
}
</script>
</body>
</html>追问

不错 我再研究研究 有问题再问你~谢谢

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-12-19
只会写jquery获取的
$("li").mouseenter(function(){
alert($(this).index())
})追问

我想用javascript 不需动用 jquery 谢谢你 帮忙再想想

第2个回答  2011-12-19
<ul><li>1</li><li>2</li><li>3</li></ul>
<script type="text/javascript">
var oLi = document.getElementsByTagName('li');
var getIndex = function(cur,obj){
for(var i=0;i<obj.length;i++){
if(obj[i] == cur){
return i;
}
}
}
var showMsg = function(){
for (var i=0;i<oLi.length;i++){
oLi[i].onclick = function(){
alert(getIndex(this,oLi));
}
}
}
oUl.addEventListener("click",showMsg(),false);
</script>
第3个回答  2011-12-19
onmouseover 事件追问

这个我懂 你没明白我的意思
比如

123
123
123
onmousevoer 这个记过第2个li 提示 下标是2 不是提示内容

参考资料:http://www.w3school.com.cn/htmldom/event_onmouseover.asp