I'm trying to pass a parameter in the onclick event. Below is a sample code:
<div id="div"></div>
<script language="javascript" type="text/javascript">
var div = document.getElementById('div');
for (var i = 0; i < 10; i++) {
var link = document.createElement('a');
link.setAttribute('href', '#');
link.innerHTML = i + '';
link.onclick= function() { onClickLink(i+'');};
div.appendChild(link);
div.appendChild(document.createElement('BR'));
}
function onClickLink(text) {
alert('Link ' + text + ' clicked');
return false;
}
</script>
However whenever I click on any of the links the alert always shows 'Link 10 clicked'!
Can anyone tell me what I'm doing wrong?
Thanks
onclick vs addEventListener. A matter of preference perhaps (where IE>9).
How abut just using a plain data-* attribute, not as cool as a closure, but..
It is probably better to create a dedicated function to create the link so you can avoid creating two anonymous functions. Thus:
Although in both cases you end up with two functions, I just think it is better to wrap it in a function that is semantically easier to comprehend.
Is a closure and stores a reference to the variable
i
, not the value thati
holds when the function is created. One solution would be to wrap the contents of thefor
loop in a function do this:Another simple way ( might not be the best practice) but works like charm. Build the HTML tag of your element(hyperLink or Button) dynamically with javascript, and can pass multiple parameters as well.
Try this:
This happens because the i propagates up the scope once the function is invoked. You can avoid this issue using a closure.
Or if you want more concise syntax, I suggest you use Nick Craver's solution.