【问题标题】:Unexpected token ILLEGAL when using setTimeout/Cleartimeout使用 setTimeout/Cleartimeout 时出现意外令牌非法
【发布时间】:2026-02-03 22:20:04
【问题描述】:

这就是我想要的:当我将鼠标悬停在 div 之外时超时,如果我再次将鼠标悬停在 div 顶部则取消。

如果我删除取消功能,该代码将起作用。所以显示和隐藏 div 效果很好。

这是我的代码:

$(document).ready(function ()
    {
        var timeoutID;
        function clearAlert()
        {
            window.clearTimeout(timeoutID);
        }​

        if ($('.txtVote').text() == "Avgi stemme")
        {
            $('#starInfo').hover(
            function ()
            {
                clearAlert();
                $('#CarDetailsButtons').css('right', '10px');
                $('#voteStars').show();
            },
            function ()
            {
                console.log("hide iniated");
                timeoutID = window.setTimeout(hideStars, 2000);
                console.log("hide executed");
            });     
        }

        function hideStars()
        {
            console.log("hideStars ran");
            $('#CarDetailsButtons').css('right', '45px');
            $('#voteStars').hide();
        }
});

而且,这是我的错误:

Uncaught SyntaxError: Unexpected token ILLEGAL

出现在window.clearTimeout(timeoutID);之后的那一行

谁能看到我做错了什么? :)

编辑: *作品*

所以,我似乎遇到了某种复制粘贴错误。我手动编写了 clearAlert 函数,就像以前一样,现在它可以工作了。

感谢大家的意见!

【问题讨论】:

  • var timeouteId;timeoutID - 更改其中之一
  • 没用 :( 但我更新了代码。仍然是同样的错误。我怀疑我什至需要 var timeoutID;
  • 将 var 移动到全局范围:window.timeoutID="";
  • 添加了 window.timeoutID="";但仍然不工作
  • 试试这个FIDDLE

标签: javascript jquery


【解决方案1】:

试试这个:

var that = this;
that.timeoutID = null;

...

that.timeoutID = ...

你必须声明 var timeoutID = null;全球的。因此,您在全局上下文中拥有 var,而不是在 $(document).ready 的函数上下文中。

最好的解决方案是编写一个带有计时器的小 js-class。所以你没有全局冲突并且它可以工作。

你好!

【讨论】:

    【解决方案2】:

    我建议您像这样将您的函数移到 doc 之外:

    function hideStars()
        {
            console.log("hideStars ran");
            $('#CarDetailsButtons').css('right', '45px');
            $('#voteStars').hide();
        }
    
    function clearAlert()
        {
            window.clearTimeout(timeoutID);
        }​
    
    $(document).ready(function ()
      {
        var timeoutID;
    
    
        if ($('.txtVote').text() == "Avgi stemme")
        {
            $('#starInfo').hover(
            function ()
            {
                clearAlert();
                $('#CarDetailsButtons').css('right', '10px');
                $('#voteStars').show();
            },
            function ()
            {
                console.log("hide iniated");
                timeoutID = window.setTimeout(hideStars, 2000);
                console.log("hide executed");
            });     
        }
    
    
    });
    

    【讨论】: