发布网友 发布时间:2022-04-30 04:25
共1个回答
热心网友 时间:2023-10-12 13:13
不能获取到,除非给每个元素都加上一个标识,标识当前元素是第几个追问加标识是怎么做呢?追答 window.onload = function(){
var imgs = getElementByClassName("pic");
for(var i=0;i<imgs.length;i++){
imgs[i].parentNode.onclick = (function(i){
return function(){
alert(i)
}
})(i)
}
}
function getElementByClassName(className){
var elems = [];
if(!document.getElementsByClassName){
alert("no exit");
var dom = document.getElementByTagName('*');
for(var i = 0;i<dom.length;i++){
if(dom[i].className == className)
elems.push(dom[i]);
}
}else{
elems = document.getElementsByClassName(className);
}
return elems;
}
用闭包吧
热心网友 时间:2023-10-12 13:13
不能获取到,除非给每个元素都加上一个标识,标识当前元素是第几个追问加标识是怎么做呢?追答 window.onload = function(){
var imgs = getElementByClassName("pic");
for(var i=0;i<imgs.length;i++){
imgs[i].parentNode.onclick = (function(i){
return function(){
alert(i)
}
})(i)
}
}
function getElementByClassName(className){
var elems = [];
if(!document.getElementsByClassName){
alert("no exit");
var dom = document.getElementByTagName('*');
for(var i = 0;i<dom.length;i++){
if(dom[i].className == className)
elems.push(dom[i]);
}
}else{
elems = document.getElementsByClassName(className);
}
return elems;
}
用闭包吧