I have a simple script which calls a function that is set in the function that the call is made…
But i get an “undefined function” error.
My script is:
function messages_document(messages){
messages = JSON.parse(messages);
function del_msg(id){
result = call_file('del.php',id);
if(result){
messages[id].length = 0;
}
}
var output = [];
output.push('<p align="center"><b><u>My Messages</u></b></p> <br/><br/>');
for(var id in messages){
output.push('<a href="#" onclick="del_msg('+id+')">Delete Message</a>');
}
document.getElementById('main').innerHTML = (output.join(''));
}
I’m curious if i have misunderstood how scope works because i get:
del_msg is not defined
Any ideas why this is ?
Function statements are defined in the current scope, not globally. In this case, that means that
del_msgexists only within the scope ofmessages_document. However, you invoke it via anonclickattribute: these attributes are evaluated globally. Sincedel_msgdoesn’t exist globally, it doesn’t work.You have two options. One is to make
del_msgglobal, by defining it outside any other functions. However, this pollutes the global namespace, generally a bad thing. Better would be to apply it to youraelement within the scope. This is going to require building the elements via DOM methods, rather than by HTML