简体   繁体   中英

Onclick = function() in javascript, showing “uncaught type error”

I am trying to do something like below.

I have 5 buttons in my site.the desire is if user press any of the button, it makes an effect of scaling down.the issue is, i don't want want all of them scale down when i click one of the buttons , so i came with this approach, but its showing me an error.so how can achieve this effect?

 items = document.querySelectorAll('.tags'); for (var iterator = 0; iterator < items.length; iterator++){ items[iterator].onclick = function () { items[iterator].style.transform = 'scale(0.9, 0.9)'; } }
 <button class='tags'>button1</button> <button class='tags'>button2</button> <button class='tags'>button3</button> <button class='tags'>button4</button> <button class='tags'>button5</button>

Use this.style.transform instead of this.style.transform

 items = document.querySelectorAll('.tags'); for (var iterator = 0; iterator < items.length; iterator++){ items[iterator].onclick = function (iterator) { this.style.transform = 'scale(0.9, 0.9)'; } }
 <button class='tags'>button1</button> <button class='tags'>button2</button> <button class='tags'>button3</button> <button class='tags'>button4</button> <button class='tags'>button5</button>

You can also use this approach,

 function animateInit(event){ event.target.style.transform = 'scale(0.9, 0.9)'; }
 <button class='tags' onclick="animateInit(event)">button1</button> <button class='tags' onclick="animateInit(event)">button2</button> <button class='tags' onclick="animateInit(event)">button3</button> <button class='tags' onclick="animateInit(event)">button4</button> <button class='tags' onclick="animateInit(event)">button5</button>

Unfortunately I can not see all your code. The problem must be in the iterator declared with var . I just changed the var for let and works fine for me.

 items = document.querySelectorAll('.tags'); for (let iterator = 0; iterator < items.length; iterator++){ items[iterator].onclick = function () { items[iterator].style.transform = 'scale(0.9, 0.9)'; } }
 <button class='tags'>button1</button> <button class='tags'>button2</button> <button class='tags'>button3</button> <button class='tags'>button4</button> <button class='tags'>button5</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM