-->

can't access elements after jQuerymobile page

2019-02-27 17:00发布

问题:

I created a simple example to illustrate my problem here: https://github.com/kanesee/jqm-page-state

Basically, I have page1.html, which has a div with id=content and I change its color to red. I have a page2.html, which has a div with id=content and I change its color to green.

When I go to page1, the color of the text in the div is red, as expected. When I go to page2, the color of the text in the div is green, as expected.

I have a simple anchor href from page1 that goes to page2. After clicking it, page2 loads and the text inside the div changes accordingly. But the color of the text is unchanged. It's black.

I've been told that when ajax handles page navigation, the page state remains in the original pages context. So when I go to page2, I'm actually still on page1 but part of the content in page2 is loaded into the DOM.

What do I need to do to get around this?

Is there a proper solution? Or even a simple one that just loads page2 entirely brand new as if I typed it into my address bar by hand?

回答1:

You are using the same id for both pages and both pages are inside the same DOM as Ajax is enabled. You have to specify which element to target and in which page.

$("#content") will return first element in DOM, hence, you need to use page events to target that element inside current page or the page you're about to navigate to. This can be achieve by using any almost all page events.

$(document).on("pagecontainershow", function () {
   var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
   if (activePage.attr("data-url") == "page2.html") {
      // target content within active page
      // Or activePage.find("#content").css...
      $("#content", activePage).css({ color : "green" });
   }
});

The above is a basic example; there are more advanced solutions.