Reputation: 14684
i have a problem with jQuery and jQueryMobile.
I have a site with 2 pages:
<div data-role="page" id="main">
<div data-role="header">
header1
</div>
<div data-role="content">
<a id="1" href="#detail">link</a>
</div>
</div>
<div data-role="page" id="detail">
<div data-role="header">
header2
</div>
<div data-role="content">
<div id="foo">content2</div>
</div>
</div>
when i press the link i save the id with jquery:
$(document).ready(function(){
var test = 0;
$('a').click(
function ()
{
test= $(this).attr('id');
}
);
});
to this point, everything is fine. the problem is, when i want to read out the var test
after i clicked the link, it is not saved anymore.
what can i do to prevent this?
i want to make something like this:
$('#foo').html(test);
Upvotes: 0
Views: 1552
Reputation: 709
var test = 0;
$('#main').live("pageshow",function(event){ //or pageinit, or pagecreate
$('a').click(
function ()
{
test= $(this).attr('id');
}
);
});
Upvotes: 1
Reputation: 85318
jQM Docs:
Important: Use
pageInit()
, not$(document).ready()
The first thing you learn in jQuery is to call code inside the
$(document).ready()
function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate, and the DOM ready handler only executes for the first page. To execute code whenever a new page is loaded and created, you can bind to the pageinit event. This event is explained in detail at the bottom of this page.
I would also suggest reading on var Scope and Closures in JavaScript
Related:
Upvotes: 2
Reputation: 76880
Reading from your comment you need to use pageInit. Have you tried
$( '#main' ).live( 'pageinit',function(event){
var test = 0;
$('a').click(
function ()
{
test= $(this).attr('id');
}
);
});
Upvotes: 2