我在使用 jQuery 和 jQueryMobile 时遇到问题。
我有一个有 2 个页面的网站:
<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>
当我按下链接时,我用 jquery 保存 id:
$(document).ready(function(){
var test = 0;
$('a').click(
function ()
{
test= $(this).attr('id');
}
);
});
到目前为止,一切都很好。问题是,当我点击链接后想读出 var test
时,它不再保存。
我可以做什么来防止这种情况发生?
我想做这样的东西:
$('#foo').html(test);
最佳答案
jQM 文档:
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.
我还建议阅读 var Scope和 Closures在 JavaScript 中
相关:
关于javascript - 多页面站点中 jQueryMobile/jQuery 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9094400/