2013-05-31 107 views
0

我正在使用jQuery Mobile的PageShow事件來設置某些輸入元素的寬度。如果我直接加載頁面(即通過URL),一切都按預期工作。jQuery Mobile PageShow無法按預期工作

如果我通過標準的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); 
    }); 

}); 

回答

1

這是一個瘋狂的猜測,但你需要改變你的邏輯。從你剛剛說的我猜你有幾個頁面相同​​ div。如果是這種情況,那麼你需要了解jQuery Mobile和JavaScript的工作原理。 jQuery Mobile使用ajax將內容加載到DOM中。一個或多個頁面可以加載。

如果您有多個頁面具有相同的DIV ID,當您嘗試訪問它時,您將訪問在具有該ID的DOM中找到的第一個元素,而且它通常不是您想要的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); 
    }); 

}); 

我不知道該代碼工作正常,但我認爲你現在應該明白這一點。

+0

哇,你真是太棒了!太感謝了。我在這裏不理解的是,所以JQM使用Ajax加載頁面並將其插入到DOM中,但爲什麼它沒有從DOM中刪除前一頁?另外,如果JS已經被加載(這樣'pageshow'事件觸發),JS如何使用Ajax加載刷新? JQM僅加載元素的內容嗎? – Lee

+0

回答你的第一個問題。兌現可以關閉,但默認情況下始終開啓。接下來的2個問題將由我的其他答案在這裏回答:http://stackoverflow.com/questions/15800121/why-i-have-to-put-all-the-script-to-index-html-in-jquery-移動/ 15806954#15806954 – Gajotres

+0

啊,我看到了,這個答案也解釋了JS的神祕http://stackoverflow.com/questions/7449402/jquery-mobile-mobile-changepage-not-loading-external-js-files。因此,如果一個人按照我所做的方式來做事情(即佈局頁面頭部的所有JS),那麼您總是需要使用$ .mobile.activePage.find('。add-on')而不是$('selector 「)? – Lee