I have connected jQuery to my html-page.
body of page:
<a>Lorem ipsum</a>
<a>dolor sit amet</a>
<a>consectetuer adipiscing elit</a>
I want to add onclick method to every link, using javascript. I wrote in head of page:
var links = $('a');
for(var i=0; i<links.length; i++)
(function(i){links[i].onclick=function(){alert(i);}})(i);
It doesn't works. I click on one of the links and nothing happens. The reason is that my javascript runs before DOM created. There is how I solved this issue:
$(function (){
var links = $('a');
for(var i=0; i<links.length; i++)
(function(i){links[i].onclick=function(){alert(i);}})(i);
});
Is my solution good? What might be better?
Aucun commentaire:
Enregistrer un commentaire