Jquery on event 不与选择器一起工作,因为它与 Jquery(document) 一起工作

Jquery on event is not working with selector where as its working with Jquery(document)?

本文关键字:Jquery 工作 一起 document 因为 选择器 event on      更新时间:2023-09-26

Jquery on event 不与选择器一起使用,因为它与 Jquery(document) 一起工作?

我已将所有页面脚本移动到js文件,一切正常,但事件处理程序附件无法使用元素选择器。

这是我移动到JS文件后面临的问题:

      $(document).ready(function () {
      //this event is not working
      $('.add-new').on('click',function(){
               //code  
      });
      //this event is working fine.
      $(document).on('click','.add-new', function(){
             //code 
      });
     });

由于一些依赖项,我使用的是jquery版本1.7.1和2.1.2

这些jQuery和Page JS文件的顺序如下。

<script src="/Scripts/modernizr-2.6.2.js"></script>
<script src="/Scripts/jquery-1.7.1.js"></script>
 //page js where from i have moved all page js to this file
<script src="/Scripts/ShowCollectionData.js"></script>
<script src="/Scripts/jquery-2.1.1.min.js"></script>
使用 $(document).on('click','

.add-new', function(){}) 将不是正确的方法。

我在某处做错了吗?

  $(document).on('click','.add-new', function(){
     //code 
  });
  $('.add-new').on('click',function(){
     //code  
  });

您的两个声明都是有效的。

前者适用于动态添加的元素。之所以使用文档,是因为您要在文档对象的子对象上委派事件,因此事件会冒泡到文档级别。选择最接近的父级也更方便(加载时父级必须存在于页面上)。

后者仍然有效,并且是将事件简单地绑定到特定元素的首选方法。

您可以在此处阅读有关 on() 的更多信息。