Uncaught SyntaxError: Unexpected token (
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); }
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 a
is not global and JavaScript inside an HTML on*
argument won't create a closure the code still doesn't work.
Here's a proper/working example using jQuery:
function test(a) {
if(a !== undefined) {
$('body').html(a);
}
else {
$('body').html('a is undefined');
}
var a = 'a is defined';
$('body').append('<br /><br />');
$('<a href="#">test</a>').click(function(e) {
e.preventDefault();
test(a);
}).appendTo('body');
}
$(document).ready(function() {
test();
});
链接地址: http://www.djcxy.com/p/45998.html