奇怪的jQuery + Chrome问题



我在根据不同元素的宽度动态调整宽度时遇到了麻烦。所以我做了一小段javascript来解决这个问题,这应该是一个实验,但一个奇怪的问题引起了我的注意。

var adjustTo = $(this).attr('data-adjust-width-to'),
    totalWidth = $(this).parent().width(),
    targetWidth = $(this).parent().find(adjustTo).width(),
    newWidth = totalWidth - targetWidth;
$(this).width(newWidth);

这在firefox, safari甚至IE7中都可以正常工作。然而,当我在Chrome中使用它时,它声称targetWidth为0,尽管当我使用控制台检查它正在调用的元素时它不是。

我设法修复它…通过将整个东西放入setTimeout中,延迟为0…

我认为这与渲染没有完成有关,但由于代码放在document.ready()函数中…不应该是这样的,对吧?

谁知道这个问题的原因是什么?

这并不常见,但请尝试拆分var调用:

var adjustTo = $(this).attr('data-adjust-width-to');
var totalWidth = $(this).parent().width();
var targetWidth = $(this).parent().find(adjustTo).width();
var newWidth = totalWidth - targetWidth;
$(this).width(newWidth);

怎么样:

var adjustTo = $(this).attr('data-adjust-width-to'),
    totalWidth = $(this).parent().width(),
    targetWidth = $(this).parent().find('#' + adjustTo).width(),
    newWidth = totalWidth - targetWidth;
$(this).width(newWidth);

我猜adjustTo是指向某个元素的ID。虽然IE并不真正关心# s,但WebKit (Chrome)确实关心。

最新更新