As a beginner in javascript, I have been struggling to find a solution for my problem for a week.
The code example I am working with is shown below (all within an HTML page in the head tag)
//example function 1
function randomString(len, charSet) {
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var randomString = '';
for (var i = 0; i < len; i++) {
var randomPoz = Math.floor(Math.random() * charSet.length);
randomString += charSet.substring(randomPoz,randomPoz+1);
}
return randomString;
}
//example function 2
function tests(randomString) {
alert(randomString);
}
//example function 3 pull data from JSON to div id test
$(document).ready(function() {
$.getJSON("http://www.test.com/get_json_data.php?", {
cat_id: "3",
type:'GET',
dataType: 'json',
}, function(data) {
$.each(data.items, function(i, item) {
$('#test').append('<a href="#" onclick="tests(randomString(5))"><img src="http://www.test.com/images/'+item.image+'"/></a>');
if (i == 10) return false;
});
});
});
My issue arises when trying to insert a variable from the JSON data (e.g. "item.id") into the "onclick" event. I attempted to achieve this using the following code:
onclick="tests(randomString(5)+item.id)"
The desired outcome is to display an alert containing 5 random characters followed by the item.id, for instance:
xIyax33 (where 33 is item.id)
TwQpu34 (where 34 is item.id)
AERim35 (where 35 is item.id)
However, I keep encountering an error stating "item is not defined."
Can anyone offer suggestions on how I can modify the code to successfully incorporate variables from the JSON data?