Dan*_*son 3 html javascript indexing html-lists
我试图在Javascript中通过id找到我的列表项的索引.例如,我有5个项目的列表,并给出一个元素,我想弄清楚它在列表中的位置.下面是我希望构建的代码.
它使用onclick处理程序来查找正在工作的元素,然后我只需要以某种方式计算元素在列表'squareList'中的位置.
window.onload=function(){
function getEventTarget(e){
var e=e || window.event;
return e.target || e.srcElement;
}
function selectFunction(e){
var target=getEventTarget(e);
alert(target.id);
}
var squareList=document.getElementById('squareList');
squareList.onclick=function(e){
selectFunction(e);
}
}
Run Code Online (Sandbox Code Playgroud)
Ble*_*der 12
要获取索引,您可以执行以下操作:
Array.prototype.indexOf.call(squareList.childNodes, target)
Run Code Online (Sandbox Code Playgroud)
使用jQuery,因为您已经在使用跨浏览器的变通方法:
$(document).ready(function() {
$('#squareList li').click(function() {
var index = $(this).index();
})
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10441 次 |
| 最近记录: |