【问题标题】:Delegate in jquery is not working as expectedjquery 中的委托未按预期工作
【发布时间】:2012-10-05 06:14:39
【问题描述】:

我使用了两个 div 并为它们的内部元素定义了点击事件 在 jquery 1.7.2 中使用委托。第一次点击事件工作正常 预期的,第二个不起作用。

 $("#first").delegate(".ask div:first","click",function(e){
   alert("hi"); 
 });

 $("#second").delegate(".ask div:first","click",function(e){
   alert("hello");
 });​

HTML 标记:

<div id="first" >
<div class="ask"> 
    <div> hi  </div>
    <div> disabled </div>
</div>

</div>

<div id="second" >
  <div class="ask"> 
     <div> hello </div>
     <div> disabled </div>
</div>

http://jsfiddle.net/YjK3N/3/ ​​​ 但在 jquery 较低版本中,上述代码按预期工作正常。

【问题讨论】:

    标签: jquery html jquery-delegate


    【解决方案1】:

    我试过了,你是对的,它不起作用。这段代码虽然有效:

    $("#first").on("click",".ask div:nth-child(1)",function(e){
      alert("hi");
    });
    
    $("#second").on("click",".ask div:nth-child(1)",function(e){
      alert("hello");
    });​
    

    【讨论】:

      【解决方案2】:

      使用:first-child,它可以工作

      $("#first").delegate(".ask div:first-child","click",function(e){
        alert("hi");
      });
      
      
      $("#second").delegate(".ask div:first-child","click",function(e){
        alert("hello");
      }) ;​
      

      它适用于.on

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多