Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript for loop and alert

Tags:

javascript

I am looping through a list of links. I can correctly get the title attribute, and want it displayed onclick. When the page is loaded and when I click on a link, all of the link titles are alerted one by one. What am I doing wrong?

function prepareShowElement () {
var nav = document.getElementById('nav');
var links = nav.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    links[i].onclick = alert(links[i].title);
    }
}
like image 946
Squadrons Avatar asked Dec 27 '22 17:12

Squadrons


1 Answers

What you were doing was actually running the alert function. enclosing the whole thing in an anonymous function will only run it when it is clicked

for (var i = 0; i < links.length; i++) {
    links[i].onclick = function () {
        alert(this.title);
       }
    }
like image 53
Ibu Avatar answered Jan 08 '23 04:01

Ibu