最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - setInterval( ) -- unexpected identifier - but it works once - Stack Overflow

programmeradmin3浏览0评论

Why do I get Uncaught SyntaxError: Unexpected identifier if it works once?

There are a bunch of these on StackOverflow. The punchline is usually a typo somewhere in the script.

It works once, then it gives 1 error message a second.

Here I am changing the colors of states on a map:

<!-- language: lang-js -->
<script type="text/javascript">
colors = [ 'rgba(255,0,0,0.1)','rgba(0,255,0,0.1)','rgba(0,0,255,0.1)'  ];

$(document).ready(function(){

    setInterval(
        $("ul").children().eq( Math.floor(50*Math.random())).css('color', colors[Math.floor(3*Math.random())] )
    ,1000);

});
</script>

Why do I get Uncaught SyntaxError: Unexpected identifier if it works once?

There are a bunch of these on StackOverflow. The punchline is usually a typo somewhere in the script.

It works once, then it gives 1 error message a second.

Here I am changing the colors of states on a map:

<!-- language: lang-js -->
<script type="text/javascript">
colors = [ 'rgba(255,0,0,0.1)','rgba(0,255,0,0.1)','rgba(0,0,255,0.1)'  ];

$(document).ready(function(){

    setInterval(
        $("ul").children().eq( Math.floor(50*Math.random())).css('color', colors[Math.floor(3*Math.random())] )
    ,1000);

});
</script>
Share Improve this question edited May 23, 2017 at 11:52 CommunityBot 11 silver badge asked Feb 20, 2013 at 16:29 john mangualjohn mangual 8,16813 gold badges58 silver badges96 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 21

You are missing function(){} to wrap your code.

setInterval(function(){
    $("ul").children().eq( Math.floor(50*Math.random())).css('color', colors[Math.floor(3*Math.random())] )
},1000);

it works once because it executes your inner-code looking for a function or string to be returned. When one isn't, it fails with a js error.

setInterval accept parametres in quotes:

<script type="text/javascript">
colors = [ 'rgba(255,0,0,0.1)','rgba(0,255,0,0.1)','rgba(0,0,255,0.1)'  ];

$(document).ready(function(){

    setInterval(
        '$("ul").children().eq( Math.floor(50*Math.random())).css("color", colors[Math.floor(3*Math.random())] )'
    ,1000);

});
</script>
发布评论

评论列表(0)

  1. 暂无评论