Delegate in jquery is not working as expected

80 Views Asked by At

I have used two div and defined click event for their inner element using delegate in jquery 1.7.2. first click event is working fine as expected and second is not working.

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

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

Html markup:

<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/ ​ But in jquery lower version the above code is working fine as expected.

2

There are 2 best solutions below

0
On

I have tried it and you are right, it's not working. This code worked though:

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

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

Use :first-child, it works

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


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

And it works with .on