I want to add an event handler to some dynamically added elements. I simplified my problem into the basic code below. I am using the new JQuery 1.7 on feature to say “hey for all labels in the CancelSurvey id element call this notify function when they are clicked.”
function notify(event) {
console.log(event.data.name);
}
$('#CancelSurvey').on('click', 'label', { name: $(this).attr("id") }, notify);
I want to pass the id of the label as parameter “name”. When I try to alert this it is undefined (they are defined in the html created). I believe that using the $(this) is not referencing the label selector in this case. It actually seems to be referencing the document itself. Any ideas on how to accomplish this?
It’s because you’re evaluating
thisof the enclosing context where the handler is assigned, therefore it isn’t a reference to the eleent.Since you know the ID, you can use a string.
Or skip the event data, and just get it from the element in the handler