can't access elements after jQuerymobile page change

半城伤御伤魂 提交于 2019-12-20 04:38:10

问题


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.



来源:https://stackoverflow.com/questions/24235047/cant-access-elements-after-jquerymobile-page-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!