Reputation: 3833
I am having some problems in my webpage.
I have a pageshow event in which I fire an ajax call to return some events from my server. After that, I populate a list with them and create a page for all events with their data with this:
$("#modifyEvent").after('<div data-role="page" id="modifyEvent'+i+'"" data-theme="a">'+
bla bla bla...
);
Each event is well recognized and I can navigate to it and seeing all its data in the new page. But, I have a some buttons inside, each one with a class associated e.g: class="buttonDelete".
Also, I have a pagecreate event in which I would wan to add all my functions related to that buttons:
$(document).on("pagecreate", '#event', function() {
$('.buttonDelete').click(function() {
I tried with classes and id but this function is never called. What is the correct way about calling function events in this case?
Upvotes: 1
Views: 20
Reputation: 31732
The issue is that you are injecting the same page(s) without removing old one(s). The pagecreate
does fire upon navigating to the dynamic page, however, your event listener(s) is attached to first element found in DOM.
/* will fire on each page one time */
$(document).on("pagecreate", "#p1", function () {
$(".button").on("click", clickHandler);
});
<!-- dynamically inject pages - both in DOM -->
<div data-role="page" id="p1">
<a class="button">Button</a> <!-- this one will always receive the binding -->
</div>
<div data-role="page" id="p1">
<a class="button">Button</a> <!-- not this one -->
</div>
Your solution is to remove dynamically injected pages before creating new ones. The easiest way is to remove a page once hidden. Simply, add a custom class e.g. dynamic
and remove any page with that class on pagecontainerhide
.
$(document).on("pagecontainerhide", function (e, data) {
if ( data.prevPage.hasClass("dynamic") ) {
data.prevPage.remove();
}
});
data.prevPage
is the page that is just hidden.
Update: .hasClass("class")
is faster than .is(".class")
.
Upvotes: 1