Reputation: 381
This is my code to dynamically set the onclick
attribute to links, but without me clicking the links itself, the alert is triggered.
window.onload = function() {
var links = document.getElementsByTagName("a");
for(var i=0;i<links.length;i++) {
elm = links[i];
elm.setAttribute("onclick", alert("you clicked a lik"));
}
}
Upvotes: 0
Views: 5699
Reputation: 41533
change the corresponding line to:
elm.setAttribute("onclick", function() { alert("you clicked a link");});
If you pass as argument a function call (such as alert('msg')
), the function is executed imediatley and the actual passed argument is the function's return value. All you have to do is wrap your eventHandler code into an anonymous function.
Also, you can declare a function that handles your event and send it's name as argument :
function handleClick() { alert("you clicked a link");}
elm.setAttribute("onclick", handleClick);
P.S. : I recommend using the addEventListener
functionality instead of plain old onEvent inline attributes :
elm.addEventListener('click', function() { alert("you clicked a link");}, false);
Upvotes: 1
Reputation: 12302
Try to put the alert statement into an anonimous function
window.onload = function()
{
var links = document.getElementsByTagName("a");
for(var i=0; i < links.length; i++)
{
links[i].setAttribute("onclick", function () {
alert("you clicked a link");
});
}
}
Upvotes: 0