我正在使用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);
});
});
答案 0 :(得分:1)
这是一个疯狂的猜测,但你需要改变你的逻辑。根据您刚才所说的,我猜您有几个页面具有相同的 .content-padd
div。如果是这种情况,那么你需要了解jQuery Mobile和javascript的工作原理。 jQuery Mobile使用ajax将内容加载到DOM中。可以加载一个或多个页面。
如果您有多个具有相同DIV ID的页面,当您尝试访问它时,您将访问在具有该ID的DOM中找到的第一个元素,并且它通常不是您想要的DIV。
要访问正确的DIV,您需要使用名为active page的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);
});
});
我不确定此代码是否正常工作但我认为您现在应该明白这一点。