为什么我的悬停事件不会在JQuery中触发? [英] Why isn't my hover event firing in JQuery?

查看:83
本文介绍了为什么我的悬停事件不会在JQuery中触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定为什么我的活动没有解雇?我只想在用户将鼠标悬停在li上时更改列表样式类型。看起来我没有遗漏任何东西,但没有任何事情发生。

I'm not sure why my event isn't firing? I simply want to change the list style type when the user hovers over an li. It doesn't look like I'm missing anything, but nothing is happening.

<%@ 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>


推荐答案

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

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

If you don't have the document.ready, that gets executed before your list items get added to the DOM, so it basically does nothing. Or move that whole section to after the list items.

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

per further discussion: It is best practice to not use document.ready, since it has to wait for everything on the page to finish loading to run. With that said, you can always put these 'initializing' blocks at the end of the html to make sure that all DOM objects are created when this is executed.

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

Or the second object is to use .live(). This function will attach an event to the result of the selector whenever an element that fits the selector is created. Now you can keep this block at the top and use:

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

现在任何时候匹配 $(。component ol li)已添加到DOM中,您的悬停功能将被附加。

Now anytime something matches $(".component ol li") is added to the DOM, your hover function will get attached.

这篇关于为什么我的悬停事件不会在JQuery中触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆