Ajouve
Ajouve

Reputation: 10049

on event not handle jquery

I don't realy understand why my on event didn't works with jquery. The html is generated after the handler but it must works:

Calendar = function(){
    this.init = function(elem, path, callback){
    this.elem = elem;
    $.ajax({
        url:path,
        type:'GET',
        context: this,
        success:function(data){
            this.data = data;
            callback();
        }
    })
}

    this.generateBase = function(){
        var base = '<div class="row-fluid" >';
        base += '<div class="span3" id="month" ></div>';
        base += '<div class="span9" id="week" ></div>';
        base += '</div>';
        $(this.elem).html(base);
    }
}

$('#month').on('click',function(){
alert('aa');
});

And I use it like that

<script type="text/javascript" >
$(document).ready(function(){
    var calendar = new Calendar();
    calendar.init('#calendar',path,function(){
        calendar.generateBase();
    });
});
</script>

I really don't understand why there is no alert on click

Thanks for your help

Upvotes: 1

Views: 25

Answers (2)

Hushme
Hushme

Reputation: 3144

try

$(document).on('click','#month',function(){
alert('aa');
});

Upvotes: 2

Adil
Adil

Reputation: 148180

You need to delegate event to parent of dynamically added element, if you do know parent to can delegate to document.

$(document).on('click', '#month',function(){
   alert('aa');
});

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, reference.

Upvotes: 2

Related Questions