2012-06-08 64 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鎖定屏幕 - 我簡化了,因爲它沒有工作。一旦「密碼」被選中,我想解鎖一個新的屏幕。 –