为什么我的悬停事件不会在JQuery中触发?

Geo*_*ton 4 jquery

我不确定为什么我的比赛没有解雇?我只想在用户将鼠标悬停在li上时更改列表样式类型.看起来我什么都不缺,但什么也没发生.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
    <link href="theme.css" rel="stylesheet" type="text/css" />
</head>
<script type="text/javascript">
  $(".component ol li").hover(function() {
          $(this).css('list-style-type', 'disc');
      }
   );
</script>
<body>
    <form id="form1" runat="server">
     <div class="component">
     <ol>
         <li><a href="#"></a>&nbsp;</li>
         <li><a href="#"></a>&nbsp;</li>
         <li><a href="#"></a>&nbsp;</li>
         <li><a href="#"></a>&nbsp;</li>
         <li><a href="#"></a>&nbsp;</li>
     </ol>
     </div>    
    </form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

sho*_*639 9

<script type="text/javascript">
  $(document).ready(function() {
     $(".component ol li").hover(function() {
          $(this).css('list-style-type', 'disc');
        }
     );
   });
</script>
Run Code Online (Sandbox Code Playgroud)

如果你没有document.ready,那么在你的列表项被添加到DOM之前就会执行它,所以它基本上什么都不做.或者将整个部分移到列表项之后.

编辑:进一步讨论:最好不要使用document.ready,因为它必须等待页面上的所有内容完成加载才能运行.话虽如此,您始终可以在html的末尾放置这些"初始化"块,以确保在执行此操作时创建所有DOM对象.

或者第二个目标是使用.live().只要创建了适合选择器的元素,此函数就会将事件附加到选择器的结果.现在您可以将此块保留在顶部并使用:

<script type="text/javascript">
   $(".component ol li").live('hover', function() {
      $(this).css('list-style-type', 'disc');
   });
</script>
Run Code Online (Sandbox Code Playgroud)

现在,只要将匹配项$(".component ol li")添加到DOM,您的悬停功能就会被附加.