Home > Article > Backend Development > javascript - Traverse img to get the current clicked img attribute
Hello everyone, I am a little nervous to ask questions for the first time. I am a novice and hope to make progress together with everyone. The problem is this. I traverse a group of img and want to get the subscript of the currently clicked img. I added a num attribute to the img to get the key of the element. How should I get the num of the current img?
<code>{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</code>
<code> //打印当前元素 function selectImg(a){ console.log(a) } </code>
I found that console.log(this.num) is undefined. I have used various methods. Now I don’t know how to get it. Please give me some guidance.
Hello everyone, I am a little nervous to ask questions for the first time. I am a novice and hope to make progress together with everyone. The problem is this. I traverse a group of img and want to get the subscript of the currently clicked img. I added a num attribute to the img to get the key of the element. How should I get the num of the current img?
<code>{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</code>
<code> //打印当前元素 function selectImg(a){ console.log(a) } </code>
I found that console.log(this.num) is undefined. I have used various methods. Now I don’t know how to get it. Please give me some guidance.
<code><div id='wrap'> <img src="image/1.jpg" alt="" num="1"> <img src="image/2.jpg" alt="" num='2'> <img src="image/3.jpg" alt="" num='3'> <img src="image/4.jpg" alt="" num='4'> </div> <script type="text/javascript"> var wrap=document.getElementById("wrap"); var imgs=wrap.getElementsByTagName('img'); console.log(imgs.length); for(var i in imgs){ imgs[i].index=i; imgs[i].onclick=function(){ alert(this.getAttribute('num')); console.log(this.index); } } </script></code>
this.getAttribute("num");
Try this
I don’t understand the principle, so I just use jq to bind a click event to the img tag. Getting this is the img you clicked. If you want to get whatever you want, just use this.getAttribute("attribute");