Update script.js

Avoid creating a function inside a loop. Solve incorrect event listener.