2014-01-20 40 views
0

這只是一對夫婦的代碼行:http://jsfiddle.net/z7bHt/jquery mouseover無法正常工作。在jfiddle工作只有

HTML:

<body> 
<img src="http://pjg.mobi/mh/images/layover_brownstring.png" id="bowleft" width="200" height="77" alt=""/> 
</body> 

JAVASCRIPT:

$("#bowleft").mouseenter(function(){ 
    console.log("worked!!!");alert("worked!!!"); 
}); 

,但這個簡單的鼠標懸停不工作,本地或遠程,無論是在鉻或Firefox!

有人可以自己試試看看我是不是瘋了,或者它是我的操作系統? https://www.dropbox.com/s/ahpaluj2e7ru9xn/mouseover.zip

+0

你包括在HTML是什麼版本的jQuery? – taxicala

回答

2

.mouseenter代碼在#bowleft元素存在之前正在運行。您需要確保它在DOM中存在該元素之後運行。有很多方法可以做到這一點。我建議你在</body>之前將你的JavaScript移動到。你也可以把它包裝:

$(function() { 

或者$(document).ready(function() {,這在功能上相同。

我也建議使用.on而不是事件後命名的特定函數,但這並不影響你在這裏。 All together:

<body> 
    <img src="http://pjg.mobi/mh/images/layover_brownstring.png" id="bowleft" width="200" height="77" alt=""/> 
    <script src="js/jquery-1.10.2.min.js"></script> 
    <script> 
     $("#bowleft").on("mouseenter", function() { 
      console.log("worked!!!"); 
     }); 
    </script> 
</body> 
0

您試圖在您的JS存在於DOM之前引用圖像。

做的最好的事情是將你的JS到剛剛結束標記之前,像這樣:

<!doctype html> 
<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Test</title> 
    </head> 

    <body> 
    <img src="http://pjg.mobi/mh/images/layover_brownstring.png" id="bowleft" width="200" height="77" alt=""/> 
    <script src="js/jquery-1.10.2.min.js"></script> 
    <script> 
     $("#bowleft").mouseenter(function(){ 
     console.log("worked!!!"); 
     alert("worked!!!"); 
     }); 
    </script> 
    </body> 
</html> 

如果你想保留它在文檔的頭,你就必須將其包裝在$(document).ready()回調中。

0

試試這個,它的工作........

<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script> 
<script type="text/javascript"> 
    $(function() { 
     $("#bowleft").mouseenter(function() { 
      console.log("worked!!!"); alert("worked!!!"); 
     }); 
    });