I have to dynamically create series of links that when clicked – change some others elements properties (src, class, text), basing on some data taken from elsewhere (json).
I’ve got such a piece of code:
// this is data I need processed
screenshots = report_data.screenshots;
// for each I'd like to create a link
for (var i=0; i < screenshots.length; i++) {
document.write('<a href="" onclick="{document.getElementById(\'the_screenshot\').src = \''+ screenshots[i].screenshotFile + '\'; ' + 'return false;}">' + screenshots[i].screenshotTitle + '</a>');
});
However proper escaping all those characters took me two hours.
I’d like to place there a call to elsewhere defined parametrized function.
Then I’d only have to input the parameters.
I tried of many various combinations of what I’ve found on stackoverflow.com
leading me to a terrible headache.
Please, help.
Accidentally, after hours of trying and retrying I asked my friend and his wise head told me to do it somewhat more sophisticated way:
The final solution looks like this (may be not exactly same, but the idea is pointed):
This way the code looks much more elegant than on the first approach.
I hope this helps those, who will have to face javascript in future.
One more thing, I used to think a detail, but it came out to be a really serious: syntax. To make a closure function do it’s work:
like this:
Now it’s an anonymous function, not just an anonymous function call. And now it works.