Trying to use the following code in a page test.html:
<script language = "javascript">
function test()
{
if (typeof a != "undefined")
{
document.body.innerHTML = "";
document.write(a);
}
else
{
document.body.innerHTML = "";
document.write("a is undefined");
}
var a = "a is defined";
document.write("<br><br>");
document.write("<a href='javascript:void(0)' onclick='function(){ test(a); }'>test</a>");
}
window.onload = function(){ test(); }
</script>
Results in the error “Uncaught SyntaxError: Unexpected token (“. How would I get the link to clear the page and display the corresponding variable?
The
function(){ test(a); }inside your onclick is the cause of the error.You’d need to use
(function(){ test(a); })to get a function expression instead of a function statement.However, since
ais not global and JavaScript inside an HTMLon*argument won’t create a closure the code still doesn’t work.Here’s a proper/working example using jQuery: