js获得元素序号给图片加单击事件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } img{ float: left; width: 200px; height: 200px; margin: 5px; } </style> <script type="text/javascript"> window.onload = function(){ // 抓所有的图片 var imgs = document.getElementsByTagName('img'); // 循环所有的图片,给每张图片都加单击事件 for (var t=0;t<imgs.length;t++) { // 给t号图片添加一个变量,用来记录序号 imgs[t].xuhao = t; // 给t图片加单击事件 imgs[t].onclick = function(){ alert(this.xuhao); // 点击图片消失,位置不保留 // this.style.display = 'none'; // 点击图片消失,位置保留 this.style.visibility = 'hidden'; } } } </script> </head> <body> <!--img[src=images/$.jpg]*20 快捷写法--> <img src="https://www.qiquanji.com/mip/data/img/dmj/201903061551840509108737.png" alt="" /> <img src="https://www.qiquanji.com/mip/data/img/dmj/201903061551840509137756.png" alt="" /> <img src="https://www.qiquanji.com/mip/data/img/dmj/201903061551840509164082.png" alt="" /> <img src="https://www.qiquanji.com/mip/data/img/dmj/201903061551840510127179.png" alt="" /> <img src="https://www.qiquanji.com/mip/data/img/dmj/201903061551840510188979.png" alt="" /> <img src="https://www.qiquanji.com/mip/data/img/dmj/201903061551840510935198.png" alt="" /> <img src="https://www.qiquanji.com/mip/data/img/dmj/201903061551840510435945.png" alt="" /> <img src="https://www.qiquanji.com/mip/data/img/dmj/201903061551840511145712.png" alt="" /> <img src="https://www.qiquanji.com/mip/data/img/dmj/201903061551840511150837.png" alt="" /> <img src="https://www.qiquanji.com/mip/data/img/dmj/201903061551840511174371.png" alt="" /> </body> </html>
1、上面代码有注解,步骤方法写得很清楚,最终效果点(运行代码)来看
本站声明:网站内容来源于网络,如有侵权,请联系我们https://www.qiquanji.com,我们将及时处理。
微信扫码关注
更新实时通知