2012-06-08 68 views
4

我试图在触发mouseenter事件时应用样式,但如果我取消注释以下未改动的选择器 - 即使文档准备停止工作。Javascript/jQuery newbie与mouseenter事件导致语法错误的错误

<body> 
<div id="1" class="button untouched"></div> 
<script src="/jquery.js"></script> 
<script> 
$(document).ready(function(){ 
    alert("JQuery is working"); 
}); 

/* 
$(".untouched").mouseenter($function(){ 
    $(this).addClass("touched"); 
}); 
*/ 
</script> 
</body> 

我下面这个网址的例子:

http://api.jquery.com/mouseenter/

我也得到了following error in Firebug

missing) after argument list 
[Break On This Error] 

$(".untouched").mouseenter($function(){ 

因为它不工作,我犯了一个错误,但我不知道是什么。我所知道的是,如果我让它运行,我的代码都不会起作用。我下载了jQuery的最新1.7.2版本,我知道它在页面上可用,因为alert()与其他注释一起运行。

+3

这是一个JavaScript语法错误,而不是一个jQuery问题。 –

+0

@JaredFarrish我怎么能检测到这个错字 - 我习惯编译语言? –

+0

谢谢大家 - 我知道这是一个愚蠢的错字 - 不知道语法虽然很难发现。 –

回答

2

在您的脚本中$(".untouched")部分应该在ready函数内。另外,

mouseenter($function(){ $符号不正确。

你最终的脚本应该是这样的:

$(document).ready(function(){ 
    alert("JQuery is working"); 

    $(".untouched").mouseenter(function(){ 
     $(this).addClass("touched"); 
    }); 
}); 
+0

没有理由将代码移动到'$(document).ready'中。 'alert(“JQuery正在工作”);'实际上并不需要在里面。 – Paulpro

+0

@ PaulP.R.O。 - 你的意思是'doc.ready'中不需要的原因是因为它所引用的元素已经在DOM中了? –

+0

@JaredFarrish是的。为什么你会等待整个DOM准备好,当你可以立即做到这一点:) – Paulpro

4

无需在函数前面的$。此外,mouseenter事件功能代码应该在文档内准备就绪。

<script> 
    $(document).ready(function(){ 
     alert("JQuery is working"); 

     $(".untouched").mouseenter(function(){ 
      $(this).addClass("touched"); 
     }); 
    }); 
</script> 
2

你有一个额外$你不应该在这个词function的前面。你可能也想删除untouched类:

$(".untouched").mouseenter(function(){ 
    $(this).removeClass("untouched").addClass("touched"); 
}); 
+0

我想知道删除类 - 因为添加依赖于CSS替换规则。我仍然试图让我的脑袋围绕jQuery语法 - 从一个C++世界:-) - 我以前有类似2 LOCS的东西 - 但这似乎更多的jQuery风格。 –

1

您可以从CSS

.untouched 
     { 
     background: green; 
     } 

    .untouched :hover 
     { 
     background: blue 
     } 

,如果你想使用.mouseover你需要的功能轻松执行这一权利jQuery中 - 一个用于当你把鼠标放在上面,当鼠标没有结束的时候。这在css中更容易,只有一个:悬停过滤器

 $('.untouched').mouseover(function() { 
       $(this).addClass('touched'); 
        }); 
     $('.untuoched').mouseout(function() { 
       $(this).removeClass('touched'); 
         }); 
+0

谢谢斯科特。实际上,我想通过将鼠标移到网格上来选择一种模式来创建这种类型的Android锁定屏幕 - 我简化了,因为它没有工作。一旦“密码”被选中,我想解锁一个新的屏幕。 –