javascript - 多页面站点中 jQueryMobile/jQuery 的问题

标签 javascript jquery jquery-mobile

我在使用 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 ScopeClosures在 JavaScript 中

相关:

关于javascript - 多页面站点中 jQueryMobile/jQuery 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9094400/

相关文章:

javascript - JavascriptExecutor 在 selenium webdriver 中是如何工作的

javascript - Highcharts 在隐藏时向图例文本添加直通线(itemHiddenStyle)

javascript - 调用 jQuery 中的对象作为回调,无法正常工作

javascript - 单击添加/删除隐藏的溢出

javascript - 目标父容器并忽略 jQuery 中子输入复选框的单击事件

jquery-mobile - 如何自定义按钮的 jQuery Mobile 主题?

JavaScript - 未捕获类型错误 : Cannot set property '0' of undefined

javascript - 如何在 AngularJS 中使用 ng Repeat 获取嵌套的 JSON 数据

javascript - 自动选择 : http or https javascript inclusion

javascript - 在 jQuery Mobile 中,点击和点击有什么区别?