遍历img取当前点击img属性

大家好,第一次提问有点紧张,本人小白,望与大家共同进步。问题是这样的,我遍历出来一组img,想要取到当前点击img的下标,我在img上加了一个num属性用来获取该元素的key,我应该怎么获取当前img的num呢?

{foreach from=$answers item=item key=key }

<img src="{$item.img}" num="{$key}" onclick="selectImg(this)" class="funny-img" 

style=" width: 23%;margin: 0 1% 4% 1%;float: left; opacity: 0.6;">     

{/foreach}


这是遍历的img

https://img4.mukewang.com/5bbd869b000172ca02340264.jpg


//打印当前元素

function selectImg(a){


    console.log(a)


}

https://img1.mukewang.com/5bbd86ab0001125707390075.jpg

我再console.log(this.num)是undefined,各种方法都用过,我现在已经不知道怎么获取了,求大神指导指导。

阿晨1998
浏览 871回答 1
1回答

幕布斯6054654

<div id='wrap'>&nbsp; &nbsp; <img src="image/1.jpg" alt="" num="1">&nbsp; &nbsp; <img src="image/2.jpg" alt="" num='2'>&nbsp; &nbsp; <img src="image/3.jpg" alt="" num='3'>&nbsp; &nbsp; <img src="image/4.jpg" alt="" num='4'></div><script type="text/javascript">&nbsp; &nbsp; var wrap=document.getElementById("wrap");&nbsp; &nbsp; var imgs=wrap.getElementsByTagName('img');&nbsp; &nbsp; console.log(imgs.length);&nbsp; &nbsp; for(var i in imgs){&nbsp; &nbsp; &nbsp; &nbsp; imgs[i].index=i;&nbsp; &nbsp; &nbsp; &nbsp; imgs[i].onclick=function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(this.getAttribute('num'));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(this.index);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript