为什么.on()在jquery中不能按预期工作

Why is .on() Not working as expected in jquery?

本文关键字:不能按 工作 jquery on 为什么      更新时间:2023-09-26

我刚刚开始学习jQuery。下面是我尝试为动态添加的div元素附加事件"mouseover"answers"mouseout"的代码。但当我尝试在浏览器中运行这个时,没有得到任何结果。我不知道怎么了。。。我搜索了jquery的.on()的用法和语法,但没有得到好的结果。。有人能告诉我,如何让我下面的代码工作吗?。。

    <html>
       <head>
          <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
          <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
          <script type="text/javascript">
             $(function(){
                 $("#divid").on("mouseover",".test", function(){
                     $(this).css("background-color", "blue");
                 }).on("mouseout",".test", function(){
                     $(this).css("background-color", "white");
                });
             });
             function AddBox(){
                var div = $("<div></div>").addClass("test").text("Another box");
                $("#divTestArea1").append(div);
             }
          </script>
      </head>
      <body>
         <div id="divTestArea1">
            <a href="javascript:void(0);" onclick="AddBox();">Add box</a>
            <div class="test" id="divid">This is a colored box</div>
         </div>
      </body>
   </html>

提前感谢…;-)

这里的问题,

您正在将动态div添加到此处的#divTestArea1 $("#divTestArea1").append(div);

但是您正在将您的事件委派给#divid,所以这次搜索不在<div id=divid>中的div类测试。

试试这个

 $("#divTestArea1").on("mouseover",".test", function(){
   ....
  }

这样,您就可以将.testdiv的mouseover事件委派给#divTestArea1。。这正是我们所需要的。。并且应该起作用。。。