【问题标题】:jQuery Mobile PageShow not working as expectedjQuery Mobile PageShow 没有按预期工作
【发布时间】:2013-05-31 12:44:42
【问题描述】:

我正在使用 jQuery Mobile 的 PageShow 事件来设置某些输入元素的宽度。如果我直接加载页面(即通过 URL),一切都会按预期工作。

如果我通过标准 ajax 导航系统(即应用内链接)加载页面,我会收到“hello”警报和正确的“span.add-on”宽度,但“div.content” -padd' 元素的宽度为零? 'div.content-padd' 是页面中所有其他元素的容器元素,并为它们提供一些填充等。所有 JS 都加载到我的 Rails 布局模板中。

我不知道这里发生了什么。我的代码如下:

$(document).bind('pageshow', function() {

alert('hello')

    $('.add-on').addClass('ui-corner-all');

    //Set the width of the input following the appends or prepends to the remaining space
    var containerWidth = $('div.content-padd').width();
    console.log('container width:' + containerWidth);

    var appendsAndPrepends = '.input-prepend, .input-append';
    $(appendsAndPrepends).each(function () {
        var remainingSpace = containerWidth - $(this).find('span.add-on').outerWidth();
        console.log('span width' + $(this).find('span.add-on').outerWidth());

        $(this).find('div.ui-input-text').outerWidth(remainingSpace);
    });

});

【问题讨论】:

    标签: jquery jquery-mobile


    【解决方案1】:

    这是一个疯狂的猜测,但你需要改变你的逻辑。根据您刚才所说,我猜您有几个页面具有相同的 .content-padd div。如果是这种情况,那么您需要了解 jQuery Mobile 和 javascript 的工作原理。 jQuery Mobile 使用 ajax 将内容加载到 DOM 中。可以加载一页或多页。

    如果您有多个具有相同 DIV id 的页面,当您尝试访问它时,您将访问在 DOM 中找到的第一个具有该 ID 的元素,而它通常不是您想要的 DIV。

    要访问正确的 DIV,您需要使用称为活动页面的 jQuery Mobile 选择器:

    $.mobile.activePage
    

    如果不测试你的代码应该是这样的:

    $(document).bind('pageshow', function() {
    
        alert('hello')
    
        $.mobile.activePage.find('.add-on').addClass('ui-corner-all');
    
        //Set the width of the input following the appends or prepends to the remaining space
        var containerWidth = $.mobile.activePage.find('div.content-padd').width();
        console.log('container width:' + containerWidth);
    
        var appendsAndPrepends = '.input-prepend, .input-append';
        $.mobile.activePage.find(appendsAndPrepends).each(function () {
            var remainingSpace = containerWidth - $(this).find('span.add-on').outerWidth();
            console.log('span width' + $(this).find('span.add-on').outerWidth());
    
            $(this).find('div.ui-input-text').outerWidth(remainingSpace);
        });
    
    });
    

    我不确定这段代码是否正常工作,但我认为您现在应该明白这一点。

    【讨论】:

    • 哇,你是正确的!太感谢了。我在这里不明白的是,所以JQM 用Ajax 加载页面并将其插入到DOM 中,但是为什么它不从DOM 中删除前一页呢?此外,如果 JS 已经加载(以便触发 'pageshow' 事件),如何通过 Ajax 加载刷新 JS? JQM 是否仅从 元素加载内容?
    • 回答您的第一个问题。兑现可以关闭,但默认情况下它总是打开的。接下来的2个问题将由我在这里的另一个答案来回答:stackoverflow.com/questions/15800121/…
    • 啊,我明白了,这个答案也解释了 JS 的奥秘stackoverflow.com/questions/7449402/…。因此,如果有人按照我的方式做事(即布局页面头部的所有 JS),那么您总是需要使用 $.mobile.activePage.find('.add-on') 而不是 $('selector ')?
    • FWIW 我看到活动页面有一个类 'ui-page-active' 应该让人们使用 $('.ui-page-active selector')
    猜你喜欢
    • 2018-03-17
    • 2019-07-13
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多