未捕获的SyntaxError:意外的令牌(

时间:2011-10-20 07:03:34

标签: javascript

尝试在页面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>

导致错误“Uncaught SyntaxError:Unexpected token(”。如何获取清除页面并显示相应变量的链接?

1 个答案:

答案 0 :(得分:4)

你的onclick中的function(){ test(a); }是导致错误的原因。

您需要使用(function(){ test(a); })来获取函数表达式而不是函数语句

但是,由于a不是全局的,并且HTML on*参数中的JavaScript不会创建闭包,因此代码仍然不起作用。


这是使用jQuery的proper/working example

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();
});
相关问题