Question:
I have an event in jQuery (version 1.5) like this:
$('#refresh_abertos').click(function(){
// aqui o código irrelevante nesta pergunta
});
It turns out that my #refresh_abertos
element is only loaded later via ajax , and the .click()
is not tied to it, how can I solve this?
Answer:
Problem
By the time your code is being read, your element doesn't exist on the page, so attaching the click
event doesn't happen.
Solution
As an alternative to already suggested, if you intend to attach an event click
on an element that does not exist yet, you can attach it to an element that is parent
, such as the body
or wrapper that is present in the page on initial load of the same.
Practical example
In the example I used setTimeout to simulate inserting an element into the DOM a bit after reading the page.
I don't know your markup , so here's an example assuming that your #refresh_abertos
element will be placed inside a div
containing the #myWrapper
ID:
$('#myWrapper').on("click", "#refresh_abertos", function() {
alert("bubu");
});
What we are doing here is attaching the click
event to the div#myWrapper
to be triggered when it has an effect on the #refresh_abertos
element.
That way you get the click
a parent element that will take effect when you click on the element that will be introduced.
The presented solution makes use of jQuery .on() available from version 1.7.