My question is the following:
I am adding an html inside my main page at runtime with JQuery which I create and add with the following code
function show_agent_add(obj_agent, div_cont){
var div_bar;
$.get("view/bar_agent.html", function(data){
div_bar = $(data);
div_bar.find(".agent-data").html(obj_agent._getFirstName());
return false;
});
}
on the other hand to this added element you want to access its click event from jquery but when debugging it does not recognize it.
function show_detail_agent(){
$(".content-agents .bar-agent-content .bar_agent").on("click", function(){
//$(this).next().toggle();
console.log("prueba");
});
}
inside the html I have a structure created from a div with a class called .bar_agent.
I would like to know what is the correct way to access the event.
Once the events are linked to DOM elements, if you dynamically add new elements, they are not associated with that event , but you must forcefully associate it.
If you have the following event on the "a" elements in the page load:
Anything you add afterwards dynamically will not be associated with that event.
I propose the following, you create a function that associates the event:
Then, on document load and after adding the dynamic element, you call the function
addAEvent()
In this way you make sure that whenever you add data, the event is added and also keep in mind that when you do the unbind(), you clean the events so that there are not many of them associated with the same DOM element and then problems.
There are probably better solutions, but I usually use this one and it works fine for me.
You can attach the handler to
document
or to one of the top level elements that contains the new element, in effect you are going the right way, if you look at the documentation of .on() you will see that it accepts as a second parameter the selector that filters the descendants of the elements. elements that trigger the event: