0

JAVA SCRIPT

$(document).ready(function() {
     $(".group").click(groupFile);

     function groupFile(){
        alert('clicked!');
     }
});
function insert()

{
    $("body").append("<div class='group' ></div>");
}

HTML

<div class='group' >
</div>

<input type="button" value="insertNewElement" id="insert" onclick="insert()"/>

when page loaded,on click div.group works well and fire groupFile and alert to me. but when inserted the new div.group.onclick div.group function groupFile does not worked? please help me

ashkufaraz
  • 5,179
  • 6
  • 51
  • 82
  • `$("
    ").click(groupFile).appendTo("body");` <-- If you don't want delegation, just bind directly to the new element you're creating. There's no need to select it when you have it right there.
    –  Nov 09 '14 at 15:07
  • ...but you'll need to put your `groupFile()` function outside of the `.ready()` callback. –  Nov 09 '14 at 15:10

3 Answers3

3

You can use jQuery on() method to delegate the events to a static ancestor as shown below:

$(document).ready(function() {
 $(document).on("click",".group",groupFile);
 function groupFile(){
    alert('clicked!');
 }
});

read more about event delegation

T J
  • 42,762
  • 13
  • 83
  • 138
  • Get rid of the `$(document).ready()` part. Doesn't make sense to wait for the document to load if you're binding to the document. That way clicks will trigger the handler even if the page hasn't finished loading. If you're going to use that level of delegation, might as well get the most out of it. –  Nov 09 '14 at 15:13
  • @squint That's a good point... But that'll leave the handler function in global scope... I don't know whether that makes a difference or not, but currently it looks like OP wants some functions inside `ready()` and some outside... not sure why, otherwise I would've changed the named handler to an anonymous function... :) – T J Nov 09 '14 at 15:17
  • 1
    Yeah... that's true. I'd probably throw it in an IIFE if that's the case, but I guess we don't know what else is going on there. I'm betting that the OP is throwing code around without much organization, but we don't know for sure. –  Nov 09 '14 at 15:20
0

You should delegate event to BODY (or document or 'usually' better to the closest static parent element) level. Using .on(), pass selector param as it:

$('body').on('click', 'div.group', function(){
     //...
});

See explanation

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
0

For dynamic elements you need to bind to event on the body:

$("body").on("click", ".group", function(e){
    alert('clicked');
});
artm
  • 8,554
  • 3
  • 26
  • 43