简体   繁体   English

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

[英]Uncaught SyntaxError: Unexpected token (

Trying to use the following code in a page test.html: 尝试在页面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? 结果为错误“未捕获的SyntaxError:意外的令牌(”。如何获取链接以清除页面并显示相应的变量?

The function(){ test(a); } function(){ test(a); } function(){ test(a); } inside your onclick is the cause of the error. function(){ test(a); }是您的onclick内部错误的原因。

You'd need to use (function(){ test(a); }) to get a function expression instead of a function statement . 您需要使用(function(){ test(a); })来获取函数表达式而不是function 语句

However, since a is not global and JavaScript inside an HTML on* argument won't create a closure the code still doesn't work. 但是,由于a不是全局的,并且HTML on*参数中的JavaScript不会创建闭包,因此代码仍然无法正常工作。


Here's a proper/working example using jQuery: 这是使用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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM