开发者

jQuery mouseover not working for li element

开发者 https://www.devze.com 2023-03-22 11:53 出处:网络
I\'m trying to make a menu based on an ul element that will show the link description underneath the link.

I'm trying to make a menu based on an ul element that will show the link description underneath the link.

So far, I have the following code (simplified a little)

      echo '
<script>
        $("#menu_1").mouseover(function() {
            $("#description").replaceWith("test");
        });
</script>

<ul cla开发者_开发百科ss="menu_top">
<li id="menu_1"><a href = "#">Test</a></li>
</ul>

<div id="description" class="menu_desc">&nbsp;
</div>

';

However, everytime I move the mouse over the li element, nothing happens.

Does anyone know what I'm doing wrong?


You need to make sure that your event assignment happens after the document has finished loading, otherwise your mouseover event has nothing to attach too:

$(document).ready(function(){

$("#menu_1").mouseover(function() {
            $("#description").replaceWith("test");
        });

});

Here's a working demo: http://jsfiddle.net/2mWb3/


#menu1 is not yet in the DOM when you run this code..

change it to

<script>
     $(function(){
        $("#menu_1").mouseover(function() {
            $("#description").replaceWith("test");
        });
      });
</script>

so that your code runs on document.ready event.


Javascript code is executed as it is encountered. This might happen before the document is actually ready. In your case, you're trying to select the #menu_1 element before it actually exists in the document. Because you almost certainly want all your jQuery code to run after the document is ready, jQuery provides a shortcut method for you:

$(function () {
    // this code is run only after the whole document is ready to go
    $("#menu_1")...
});
0

精彩评论

暂无评论...
验证码 换一张
取 消