简体   繁体   English

Javascript-SyntaxError:意外令牌}

[英]Javascript - SyntaxError: Unexpected token }

When I try to make <div id="test">this should go down</div> go down with: 当我尝试进行<div id="test">this should go down</div>请执行以下操作:

<div onclick="(".test").slideDown(800);">close it</div>

I get this error everytime i click 'close it' 我每次点击“关闭”都会收到此错误

 SyntaxError: Unexpected token }

Please let me know, what I'm doing wrong. 请让我知道,我做错了。 Thanks :) 谢谢 :)

Try like this: 尝试这样:

<div onclick="$('.test').slideDown(800);">close it</div>

or even better as it seems that you are using jquery: 甚至更好,因为您似乎正在使用jquery:

<div id="close">close it</div>

and in a separate javascript file: 并在单独的javascript文件中:

$('#close').click(function() {
    $('.test').slideDown(800);
});

See how cleaner this is? 看看这有多清洁? You no longer need to mix markup with javascript and have problems as the one you are encountering currently. 您不再需要将标记与javascript混合在一起,而不必像当前遇到的那样遇到问题。

Change on of the uses of double quotes (and I'm guessing you're using jQuery so you'll also need to add the $ shortcut (or full jQuery call): 更改双引号的用法(我猜您正在使用jQuery,因此还需要添加$快捷方式(或完整的jQuery调用):

onclick="$('.test').slideDown(800);"

// or

onclick='$(".test").slideDown(800);'

You are using an ID selector for the <div id="test"> but trying to use a class selector to animate the <div> with $(.test ) which will never match. 您正在为<div id="test">使用ID选择器,但尝试使用类选择器为$(.test <div> $(.test .test)设置<div>动画,该动画将永不匹配。 However your code is also has bad quotes which is causing the SyntaxError, so to fix everything one of the following should help :-) 但是,您的代码也有引号错误,这会导致SyntaxError,因此,修复以下所有问题之一应该会有所帮助:-

HTML: HTML:

<div id="closeIt">close it</div>

JavaScript: JavaScript:

$('#closeIt').click(function() {
    $('#test').slideDown(800);
});

or Complete example (with separate bound function): 或完整示例(具有单独的绑定函数):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            $('#closeIt').click(function() {
                $('#test').slideDown(800);
            });
        });
    </script>
    <style type="text/css">
        #test {
            display:none;
        }
    </style>
</head>
<body>
<div>
<div id="closeIt">close it</div>
<div id="test">this should go down</div>
</div>
</body>
</html>

or inline onclick (not recommended as this doesn't separate markup from behaviour but it still works) 或内联onclick(不建议这样做,因为这不会将标记与行为分开,但仍然可以使用)

<div onclick="$('#test').slideDown(800);">close it</div>

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

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